Thank you for taking the time to read and review my post. I've done a lot of Google searching but have yet to find the answer to my jquery/asp.net question. My issue is I'm trying to replace the standard check box with an on/off image. There is a neat tutorial about doing this here. My issue is that my asp OnCheckedChanged check box event is not being called when Jquery places a check in the check box.
ASP.NET Master Page Scripts that works
<link href="~/Styles/jquery.tzCheckbox.css" rel="stylesheet" type="text/css" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript" src="<%#ResolveUrl("~/Scripts/jquery.tzCheckbox.js") %>"></script>
<script type="text/javascript" src="<%#ResolveUrl("~/Scripts/script.js") %>"></script>
Aspx Page with Checkbox
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<asp:DetailsView ID="DetailsView1" runat="server" Height="16px" Width="575px">
<Fields>
<asp:TemplateField>
<EditItemTemplate>
<asp:CheckBox ID="Edit_CheckBox1_CB" runat="server" AutoPostBack="true" OnCheckedChanged="Edit_CheckBox1_CB_Clicked" />
</EditItemTemplate>
<InsertItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
</InsertItemTemplate>
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Fields>
</asp:DetailsView>
JQuery Script called script.js
(function ($) {
$.fn.tzCheckbox = function (options) {
// Default On / Off labels:
options = $.extend({
labels: ['ON', 'OFF']
}, options);
return this.each(function () {
var originalCheckBox = $(this),
labels = [];
// Checking for the data-on / data-off HTML5 data attributes:
if (originalCheckBox.data('on')) {
labels[0] = originalCheckBox.data('on');
labels[1] = originalCheckBox.data('off');
}
else labels = options.labels;
// Creating the new checkbox markup:
var checkBox = $('<span>', {
className: 'tzCheckBox ' + (this.checked ? 'checked' : ''),
html: '<span class="tzCBContent">' + labels[this.checked ? 0 : 1] +
'</span><span class="tzCBPart"></span>'
});
// Inserting the new checkbox, and hiding the original:
checkBox.insertAfter(originalCheckBox.hide());
checkBox.click(function () {
checkBox.toggleClass('checked');
var isChecked = checkBox.hasClass('checked');
// Synchronizing the original checkbox:
originalCheckBox.attr('checked', isChecked);
checkBox.find('.tzCBContent').html(labels[isChecked ? 0 : 1]);
if (isChecked) {
originalCheckBox.attr('checked', isChecked);
}
});
// Listening for changes on the original and affecting the new one:
originalCheckBox.bind('change', function () {
checkBox.click();
});
});
};
})(jQuery);
CSS file
.tzCheckBox{
background:url("../Images/background01.png") no-repeat right bottom;
display:inline-block;
min-width:60px;
height:33px;
white-space:nowrap;
position:relative;
cursor:pointer;
margin-left:14px;
}
.tzCheckBox.checked{
background-position:top left;
margin:0 14px 0 0;
}
.tzCheckBox .tzCBContent{
color: white;
line-height: 31px;
padding-right: 38px;
text-align: right;
}
.tzCheckBox.checked .tzCBContent{
text-align:left;
padding:0 0 0 38px;
}
.tzCBPart
{
background:url("../images/background01.png") no-repeat left bottom;
width:14px;
position:absolute;
top:0;
left:-14px;
height:33px;
overflow: hidden;
}
.tzCheckBox.checked .tzCBPart{
background-position:top right;
left:auto;
right:-14px;
}
Last Note
Everything works as needed, I just can't seen to get the page to auto post when JQuery checks the check box. Thank you again for your help!
Changes made through javascript will not fire events such as onclick or onchange. What you will need to do is fire the event yourself once you change the value of checked. I am not familiar with the particulars of .net's OnCheckedChanged, but let's assume in the html it turns into onchange (you will need to verify this through viewing the source). You would do something like this:
originalCheckBox.attr('checked', isChecked);
originalCheckBox.change(); // will call the onchange code
Related
I need to create a dropdownlist where in the user can select a value from the dropdownlist or type the value in.
Exactly like the "Where do you come from ? " dropdown in the below link :
http://www.dhtmlgoodies.com/scripts/form_widget_editable_select/form_widget_editable_select.html
I know it is a common question and there are similar queries on stack overflow as well but I couldn't find a simple working solution.
I have referred the following links :
http://www.codeproject.com/Articles/8578/Editable-Dropdown-DHTML-Behavior
http://www.codeproject.com/Articles/290218/Custom-ASP-NET-Editable-DropDownList
http://codeverge.com/asp.net.web-forms/editable-dropdown-list-c/392261
Has anyone worked on this before and give me an idea as to how I can proceed ?
Another solution is as follows
You could use the Ajax Control Toolkit Nuget
Step 1:
Add the Ajax Control Toolkit from the Nuget Packages in your references
Step 2:
If you do not get the Ajax Control Toolkit controls into your Toolbox, you need to create a separate Tab and name it Ajax Toolkit Controls.
Then right click on it and select choose items.
Browse to location where the Ajax Control Toolkit's dll is located, select it.
You will see set of controls getting populated into the window.
Select Ok, this will result into populating the tab with the Ajax Control Toolkit Controls.
Step 3:
Since Ajax Toolkit Controls are an extra add-on package, you need to register them as a part of the page using them.If installed as a nuget, this step can be neglected.
<%# Register assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" tagprefix="ajaxToolkit" %>
Note: The tagprefix should match the tagprefix used by you in your program for the AjaxControlToolkit Controls.
Step 4:
Add the ScriptManager Control, It is required for providing support for client-side AJAX features. As a result it loads and registers the Microsoft AJAX library to enable the features.
<asp:ScriptManager ID="ScriptManager1" runat="server" />
Step 5:
Proceed by adding the ComboBox from the toolbox and configure it by linking it to your database using the SQLDataSource
The complete source code is as follows
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="AjaxComboboxSample.aspx.cs" Inherits="StacksEmptied.AjaxComboboxSample" %>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajaxToolkit" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<style type="text/css">
#ComboBox1_ComboBox1_OptionList {
width: 10% !important;
}
</style>
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<ajaxToolkit:ComboBox ID="ComboBox1" AppendDataBoundItems="True" runat="server" AutoCompleteMode="Suggest" DataSourceID="SqlDataSource1" DataTextField="Fruits" DataValueField="Fruits" MaxLength="0" Style="display: inline;">
</ajaxToolkit:ComboBox>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:FruitsConnectionString %>" SelectCommand="SELECT * FROM [Fruits]"></asp:SqlDataSource>
</div>
</form>
</body>
</html>
I have tested this code on all the below settings Testing Environment:
Chrome Browser Version 43.0.2334.0 dev-m (64-bit)
Internet Explorer 11
Firefox 36.0.1
Visual Studio 2013 edition
You can try using JqueryUI Autocomplete Combobox.
It will let you type in text as well as select the item of your choice from a dropdown.
As an extra feature it lets you use the autocomplete feature to get a enhance UI experience.
I am attaching a demo which is coupled with bootstrap 3.3.4
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet" />
<link href="https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css" rel="stylesheet" />
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<link href="https://jqueryui.com/resources/demos/style.css" rel="stylesheet" />
<style>
.custom-combobox {
position: relative;
display: inline-block;
}
.custom-combobox-toggle {
position: absolute;
top: 0;
bottom: 0;
margin-left: -1px;
padding: 0;
}
.custom-combobox-input {
margin: 0;
padding: 5px 10px;
}
.ui-state-default,
.ui-widget-content .ui-state-default,
.ui-widget-header .ui-state-default {
border: 1px solid #421D1D;
background: #ffffff url("images/ui-bg_glass_75_e6e6e6_1x400.png") 50% 50% repeat-x !important;
font-weight: normal;
color: #555555;
}
/* Corner radius */
.ui-corner-all,
.ui-corner-top,
.ui-corner-left,
.ui-corner-tl {
border-top-left-radius: 0px !important;
}
.ui-corner-all,
.ui-corner-top,
.ui-corner-right,
.ui-corner-tr {
border-top-right-radius: 0px !important;
}
.ui-corner-all,
.ui-corner-bottom,
.ui-corner-left,
.ui-corner-bl {
border-bottom-left-radius: 0px !important;
}
.ui-corner-all,
.ui-corner-bottom,
.ui-corner-right,
.ui-corner-br {
border-bottom-right-radius: 0px !important;
}
</style>
<script>
(function($) {
$.widget("custom.combobox", {
_create: function() {
this.wrapper = $("<span>")
.addClass("custom-combobox")
.insertAfter(this.element);
this.element.hide();
this._createAutocomplete();
this._createShowAllButton();
},
_createAutocomplete: function() {
var selected = this.element.children(":selected"),
value = selected.val() ? selected.text() : "";
this.input = $("<input>")
.appendTo(this.wrapper)
.val(value)
.attr("title", "")
.addClass("custom-combobox-input ui-widget ui-widget-content ui-state-default ui-corner-left")
.autocomplete({
delay: 0,
minLength: 0,
source: $.proxy(this, "_source")
})
.tooltip({
tooltipClass: "ui-state-highlight"
});
this._on(this.input, {
autocompleteselect: function(event, ui) {
ui.item.option.selected = true;
this._trigger("select", event, {
item: ui.item.option
});
},
autocompletechange: "_removeIfInvalid"
});
},
_createShowAllButton: function() {
var input = this.input,
wasOpen = false;
$("<a>")
.attr("tabIndex", -1)
.attr("title", "Show All Items")
.tooltip()
.appendTo(this.wrapper)
.button({
icons: {
primary: "ui-icon-triangle-1-s"
},
text: false
})
.removeClass("ui-corner-all")
.addClass("custom-combobox-toggle ui-corner-right")
.mousedown(function() {
wasOpen = input.autocomplete("widget").is(":visible");
})
.click(function() {
input.focus();
// Close if already visible
if (wasOpen) {
return;
}
// Pass empty string as value to search for, displaying all results
input.autocomplete("search", "");
});
},
_source: function(request, response) {
var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i");
response(this.element.children("option").map(function() {
var text = $(this).text();
if (this.value && (!request.term || matcher.test(text)))
return {
label: text,
value: text,
option: this
};
}));
},
_removeIfInvalid: function(event, ui) {
// Selected an item, nothing to do
if (ui.item) {
return;
}
// Search for a match (case-insensitive)
var value = this.input.val(),
valueLowerCase = value.toLowerCase(),
valid = false;
this.element.children("option").each(function() {
if ($(this).text().toLowerCase() === valueLowerCase) {
this.selected = valid = true;
return false;
}
});
// Found a match, nothing to do
if (valid) {
return;
}
// Remove invalid value
this.input
.val("")
.attr("title", value + " didn't match any item")
.tooltip("open");
this.element.val("");
this._delay(function() {
this.input.tooltip("close").attr("title", "");
}, 2500);
this.input.autocomplete("instance").term = "";
},
_destroy: function() {
this.wrapper.remove();
this.element.show();
}
});
})(jQuery);
$(function() {
$("#combobox").combobox();
$("#toggle").click(function() {
$("#combobox").toggle();
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<div class="ui-widget">
<select id="combobox" class="form-control">
<option value="">Select your option</option>
<option value="Apple">Apple</option>
<option value="Banana">Banana</option>
<option value="Cherry">Cherry</option>
<option value="Date">Date</option>
<option value="Fig">Fig</option>
<option value="Grape">Grape</option>
<option value="Kiwi">Kiwi</option>
<option value="Mango">Mango</option>
<option value="Orange">Orange</option>
<option value="Pumpkin">Pumpkin</option>
<option value="Strawberry">Strawberry</option>
<option value="Tomato">Tomato</option>
<option value="Watermelon">Watermelon</option>
</select>
</div>
</div>
</form>
</body>
</html>
I have tested this code on all the below settings
Testing Environment:
Chrome Browser Version 43.0.2334.0 dev-m (64-bit)
Internet Explorer 11
Firefox 36.0.1
Visual Studio 2013 edition
Hope this solves your issue.
This JQuery plugin will solve your problem, it turns DropDown lists into auto-complete like fields, even though it changes the HTML structure of the select element ASP.NET is still able to detect which option was selected.
Source: https://github.com/indrimuska/jquery-editable-select
OBS: To persist data to postback you need to bind the events associated with postback with JavaScript, make the "Combo Box" a dropdownlist again (with the persisted value).
Sample Usage:
$('#editable-select').editableSelect();
<link href="//rawgithub.com/indrimuska/jquery-editable-select/master/dist/jquery-editable-select.min.css" rel="stylesheet">
<select id="editable-select">
<option>Alfa Romeo</option>
<option>Audi</option>
<option>BMW</option>
<option>Citroen</option>
</select>
<script src="//code.jquery.com/jquery-1.12.4.min.js"></script>
<script src="//rawgithub.com/indrimuska/jquery-editable-select/master/dist/jquery-editable-select.min.js"></script>
I have two controls in my web form. One is combo box control, and the other is text box. What I want to do is when user selects another item in combo box, the new item is added to text box and shown to user automatically.
For example:
1. When user select '001' item in combo box, text box shows '001' in text area.
2. When user select '002' item in combo box, text box shows like this: '001','002'
Here is my code:
class webform : System.Web.UI.Page{
private StringBuilder sb = new StringBuilder();
protected void ComboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
//Todos: Add the selection of combo box to text box2.
this.localsb.Append(this.ComboBox1.Text);
this.localsb.Append(",");
this.Text2.Text = this.localsb.ToString();
}
......
}
Here is my front end code:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="PCA_Form.aspx.cs" Inherits="WebApplication2.PCA_Form" Culture="auto" meta:resourcekey="PageResource1" UICulture="auto" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>PCA_Form</title>
<style type="text/css">
#Text1 {
width: 147px;
margin-top: 0px;
}
#form1 {
height: 718px;
width: 963px;
}
.auto-style1 {
font-size: large;
}
#Checkbox1 {
width: 112px;
}
#Select1 {
width: 162px;
}
</style>
<script>
$(document).ready(function () {
$('.ComboBox1').on('blur', function () {
if ($(this).prop('checked')) {
var initial = $('#Text2').val();
var checkbox = $(this).text();
$('#Text2').val(initial + ',' + checkbox).change();
}
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<div style="height: 51px; width: 906px;" aria-atomic="False" draggable="auto">
<span class="auto-style1">New Price</span>
<asp:TextBox ID="Text1"
runat="server"
class="Text"
onkeypress="if (event.keyCode!=46 && (event.keyCode < 48 || event.keyCode >57)) event.returnValue = false;"
TextMode ="MultiLine">
</asp:TextBox>
<span class="auto-style1">Item Number</span>
<ajaxToolkit:ComboBox ID="ComboBox1"
TextMode="MultiLine"
runat="server"
AutoPostBack="True"
DataSourceID="SqlDataSource1"
DataTextField="Code"
DataValueField="Code"
Style="display: inline;"
AutoCompleteMode="Suggest"
DropDownStyle="DropDown"
OnSelectedIndexChanged="ComboBox1_SelectedIndexChanged">
</ajaxToolkit:ComboBox>
<asp:Button ID="Button1"
Text="submit"
OnClick="SubmitButton_Click"
runat="server" />
<asp:Button ID="Button2" runat="server" Text="Excel" OnClick="Button2_Click" />
<asp:TextBox ID="Text2" runat="server" TextMode="MultiLine"></asp:TextBox>
</div>
<div style="height: 466px; width: 943px; margin-top: 35px">
<span class="auto-style1"> <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="Data Source=XXX;Initial Catalog=XXXXX;Integrated Security=True" ProviderName="System.Data.SqlClient" SelectCommand="SELECT [Code] FROM [Item]"></asp:SqlDataSource>
<br />
<asp:GridView ID="PCADataGrid" runat="server" Width="938px" OnSelectedIndexChanged="PCADataGrid_SelectedIndexChanged" AutoGenerateColumns ="true">
</asp:GridView>
</span>
</div>
</form>
<p> </p>
</body>
</html>
In combo box tag, I trigger a function called ComboBox1_SelectedIndexChanged() when user changes selection in this box.
Well, that is indeed possible. However, your approach will require an Update Panel and all the agony that follows if you intend to avoid the lovely screen-flicker from those pesky Postback's. I would recommend doing this client side with JavaScript:
$(document).ready(function() {
$('.Checkbox').on('blur', function() {
if($(this).prop('checked')) {
var initial = $('#txtField').val();
var checkbox = $(this).text();
$('#txtField').val(initial + ', ' + checkbox).change();
}
});
});
That is a bit crude and rough, but it should meet your needs. This will avoid the issues your bound to introduce by using the Asp.Net Page Life Cycle. Hopefully this points you in good direction.
As I said above your approach will:
Require Postback or Update Panel
Problem:
Postback - Screen will flicker, plus can make managing View State quite difficult.
Update Panel - A pain to work with, also will hinder performance. As each 'Postback' becomes an Ajax call of the page. Which is stored in memory, so every Postback becomes stored in memory during the life-cycle. So it isn't very efficient.
Update:
You asked a question about:
.Checkbox
#txtField
On your front-end, in source code your elements are created like:
<asp:TextBox
id="txtField" runat="server"
placeholder="Initial Content..." />
There are more you can place on the control, but to answer your question they correlate to the Id or Class name for the given element your manipulating. An Id can only be bound to a single element, where a class can be used on several elements. For example-
<asp:Checkbox
id="chkField" runat="server"
CssClass="Checkbox" />
So in this instance the . is an anchor on this case, .Checkbox. The next would be # which is to anchor to the Id, #chkField. So when you use JavaScript they use the $('.Checkbox') or $('#chkField') as the Selector to elements on your page. Does that clarify for you?
I have a web page that has a master file. The master file has an update panel that contains a timer, used for showing adds/images every so many seconds. However the page's content place holder is not contained within the update panel. This is the basic markup of the master page:
<head id="hdMain" runat="server">
<title>Main Master Page</title>
<link href="~/Style/custom-theme/jquery-ui-1.10.1.custom.min.css" rel="stylesheet" />
<asp:ContentPlaceHolder
ID="cpHead"
runat="server">
</asp:ContentPlaceHolder>
</head>
<body style="margin-bottom: 0px; margin-left: 0px; margin-right: 0px; margin-top: 0px" scroll="no">
<form id="frmMain" runat="server">
<asp:ScriptManager
ID="smMain"
runat="server">
</asp:ScriptManager>
<div style="height: 671px; width: 1024px; z-index: 0;">
<asp:ContentPlaceHolder
ID="cpMain"
runat="server">
</asp:ContentPlaceHolder>
</div>
<div style="background-color: #192646; height: 97px; width: 1024px">
<asp:UpdatePanel
ID="upMain"
runat="server"
UpdateMode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="tmrMain" />
</Triggers>
<ContentTemplate>
<asp:Timer
ID="tmrMain"
runat="server"
Interval="10000"
OnTick="RotateImage">
</asp:Timer>
<img
id="imgMain"
runat="server"
height="97"
width="1024"
alt=""
src="" />
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>
Now, when my page loads, I need to do some server side processing before deciding if I want to fire up a jQuery dialog. I am using the code below in my code behind to do this:
if (NeedToRunStartupScript())
{
ClientScript.RegisterStartupScript(this.GetType(), "RedirectScript", "Sys.Application.add_load(function() { OpenDialog(); });", true);
}
The OpenDialog() is defined as following in the markup, withing the header content place holder:
<script type="text/javascript" src="../Scripts/JQuery/jquery-1.9.1.js"></script>
<script type="text/javascript" src="../Scripts/JQuery/jquery-ui-1.10.1.custom.min.js"></script>
<script type="text/javascript">
function OpenDialog() {
$(function () {
var redirectSomewhere = false;
var newDialog = $('<div title="Dialog">\
<p>Do you wish to redirect?</p>\
</div>');
newDialog.dialog({
height: 250,
width: 300,
modal: true,
buttons: {
Yes: function () {
redirectSomewhere = true;
$(this).dialog("close");
},
No: function () {
$(this).dialog("close");
}
},
close: function () {
if (redirectSomewhere) {
window.location.href = "SomePage.aspx";
}
}
});
});
};
Pretty standard stuff really. And this code works. However, each time a timer clicks and updates the image, the dialog window shows up again, so if I let it just sit there for several minutes, I will have tens of dialog windows on top of one another. I basically need my dialog to be registered only once, and not be reinitialized on every partial postback. Any help would be appreciated.
Have you tried checking for async postback like this
bool isAsyncPostback = ScriptManager.GetCurrent(this).IsInAsyncPostBack;
if (NeedToRunStartupScript() && !isAsyncPostback)
{
ClientScript.RegisterStartupScript(this.GetType(), "RedirectScript", "Sys.Application.add_load(function() { OpenDialog(); });", true);
}
I basically want to ask this question(How to implement "select all" check box in HTML?) but from a asp.net point of view. There seems to be more challenges to over come when you are using asp.net to do this. The CssClass attribute generates a span container with the class you specified and it doesn't get placed on the input. Along with the challenge of masterpages and controls. I am looping through records and displaying them with a checkbox. I was hoping to grab all the checkboxes by class to perform the check all. I don't think that will be possible. Any advice?
Markup:
<asp:CheckBox runat="server" ID="checkAll" CssClass="CheckAll" />
<asp:Table ID="tblitems" Visible="false" Width="80%" HorizontalAlign="Center" runat="server">
<asp:TableRow>
//The data gets added as a table row.
</asp:TableRow>
</asp:Table>`
Browser:
//Check All check box
<span class="CheckAll"><input id="ctl00_ContentPlaceHolder1_checkAll" type="checkbox" name="ctl00$ContentPlaceHolder1$checkAll" /></span>
//Each checkbox that will be checked looks like this
<span class="chkBox"><input id="ctl00_ContentPlaceHolder1_ctl01" type="checkbox" name="ctl00$ContentPlaceHolder1$ctl01" /></span>
JavaScript
$('.CheckAll').click(function (event) {
alert("start");
if (this.checked) {
// Iterate each checkbox
$(':checkbox').each(function () {
this.checked = true;
});
alert("end");
}
});
ClientIDMode property of the checkbox control will allow you to more easily work with client-side selectors, like this:
Markup:
<asp:CheckBox runat="server" ID="checkAll" CssClass="CheckAll" ClientIDMode="Static" />
Check out the Control.ClientIDMode Property MSDN documentation.
Note: ClientIDMode is available in ASP.NET 4.0 and later.
Since each checkbox is in a span with a class 'chkBox', locate the checkboxes using that selector on the click handler:
$('.CheckAll').on('click', function (event) {
var checked = $(this).prop('checked');
$('.chkBox :checkbox').prop('checked', checked);
});
It would be more precise if you wrapped all the checkboxes you'd like to have checked in a container div:
<div id="myCheckboxes">
// .NET code here
</div>
JS:
$('.CheckAll').on('click', function (event) {
var checked = $(this).prop('checked');
$('#myCheckboxes :checkbox').prop('checked', checked);
});
Karl, I believe, has improved the approach. However, if you want to stick with what you have, modify your Javascript to be the following:
$('.CheckAll').find(':checkbox').click(function (event) {
alert("start");
if (this.checked) {
// Iterate each checkbox
$(':checkbox').each(function () {
this.checked = true;
});
alert("end");
}
});
The following code basically selectes all checkboxes, and change the check statuses based on the CheckAll Checkbox.
<script type="text/javascript">
$(document).ready(function () {
$('#<%= CheckAll.ClientID %>').click(function() {
var checkedStatus = this.checked;
$("input[type='checkbox']").attr('checked', checkedStatus);
});
});
</script>
<asp:CheckBox runat="server" ID="CheckAll" />
<asp:CheckBox runat="server" ID="Check1" />
<asp:CheckBox runat="server" ID="Check2" />
<asp:CheckBox runat="server" ID="Check3" />
<asp:CheckBox runat="server" ID="Check4" />
Multiple Group of CheckBoxes in a Single Page
If you have multiple groups of checkboxes in a single page, you can differentiate them with class.
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs"
Inherits="WebApplication2012.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
// Selects all enabled checkboxes
$("#<%= CheckAll.ClientID %>").click(function () {
var checkedStatus = this.checked;
$(".myCheckBox input[type='checkbox']").attr('checked', checkedStatus);
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:CheckBox runat="server" ID="CheckAll" Text="Check All" CssClass="myCheckAll" /><br />
<asp:CheckBox runat="server" ID="Check1" Text="Check1" CssClass="myCheckBox" /><br />
<asp:CheckBox runat="server" ID="Check2" Text="Check2" CssClass="myCheckBox" /><br />
<asp:CheckBox runat="server" ID="Check3" Text="Check3" CssClass="myCheckBox" /><br />
<asp:CheckBox runat="server" ID="Check4" Text="Check4" CssClass="myCheckBox" />
</form>
</body>
</html>
I got it to work using this script below. This not work for every scenario but it worked very well for mine so far. Thanks!
mark up
<asp:CheckBox runat="server" ID="CheckAll" OnClick="toggle(this)" />
Javascript
function toggle(source) {
checkboxes = document.getElementsByTagName('input');
for (var i = 0, n = checkboxes.length; i < n; i++) {
checkboxes[i].checked = source.checked;
}
}
I am using this code to show a dialog box that will confirm for a delete button, it works fine, but when it pops up it doesn't disable any controls of ASP.Net page, so I can click on any of the controls or text boxes,
First thing I wanna do is fade out the page when Jquery opens my Div tag BOX and second to disable all the controls.
here's the code
Div (Custom Dialouge box)
<div id="divConfMessage">
<div align="center">
<br /><asp:Label ID="Label1" runat="server" Text="Deleting this eDecision will remove all site content and uploaded documents. Are you sure you wish to continue?" CssClass="headertext"></asp:Label><br /><br /><br /><br /><br />
<asp:Button ID="btnConfOK" Width="200px" Height="25px" CssClass="gradientbutton" OnClick="btDelete_Click" Runat="server" Text="Yes"></asp:Button>
<asp:Button ID="btnConfCancel" Width="200px" Height="25px" CssClass="gradientbutton" Runat="server" Text="No"></asp:Button><br /><br /><br />
</div>
</div>
Script (jquery)
<script type="text/javascript" src="/_layouts/1033/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("input[id$='btDelete']").click(function()
{
$("#divConfMessage").fadeIn();
});
});
</script>
Button
<td>
<asp:Button ID="btDelete" runat="server" CssClass="gradientbutton" OnClick="btDelete_Click"
OnClientClick="this.disabled=true;this.value='Please Wait...';" Text="Delete" Width="200px" />
</td>
Css for Dialog Box
#divConfMessage
{
position: absolute;
width: 500px;
height: 200px;
top: 50%;
left: 30%;
margin-left: -150px; /* Negative half of width. */
margin-top: -100px; /* Negative half of height. */
border: 2px solid #000;
DISPLAY:none;
background-color:White;
line-height:20px;
text-align:center;
}
Note
All of the code is in ASP content place holder for the page except CSS, I have 2 another Contents with different controls + a Master Page defining all these Content Place holders.
<asp:Content ID="Content4" ContentPlaceHolderID="cphSubmit" runat="server">
<%# Page Language="C#" MasterPageFile="~/my.Master" AutoEventWireup="true" CodeBehind="c.aspx.cs" Inherits="a.b.c" Title="e" meta:resourcekey="PageResource1" %>
set Modal=true; for dilogbox there is modal property, you can set it as True.
try using Jquery dialogue box ( it comes with JqueryUI plugin).
$( "#YourDivorContainerToShowAsDialog" ).dialog({
modal: true,
buttons: {
Ok: function() {
$( this ).dialog( "close" );
}
}
});
EDIt: if you don't want to use buttons, then use like this
$( "#YourDivorContainerToShowAsDialog" ).dialog({
modal: true
});
or if you want to use CSS then you can try
#YourDivorContainerToShowAsDialog
{
position: absolute;
Z-index: withMaxValue
}
Give a higher Z-index for #divConfMessage and then the modal dalog will be on top everything.
When you add a dialog append it to body as this way:
add_block_page();
add_modal_box();
function add_block_page(){
var block_page = $('<div class="page"></div>');
$(block_page).appendTo('body');
}
function add_modal_box(){
var pop_up = $('<div id="divConfMessage"></div>');
$(pop_up).appendTo('.page');
}
Use one transperant image to fadeout the page.
Add one outerDiv and apply the image to the div.
<div id="outerDiv" style="display:none;">
<div id="divConfMessage">
<div align="center">
<br /><asp:Label ID="Label1" runat="server" Text="Deleting this eDecision will remove all site content and uploaded documents. Are you sure you wish to continue?" CssClass="headertext"></asp:Label><br /><br /><br /><br /><br />
<asp:Button ID="btnConfOK" Width="200px" Height="25px" CssClass="gradientbutton" OnClick="btDelete_Click" Runat="server" Text="Yes"></asp:Button>
<asp:Button ID="btnConfCancel" Width="200px" Height="25px" CssClass="gradientbutton" Runat="server" Text="No"></asp:Button><br /><br /><br />
</div>
</div>
</div>
CSS for outerDiv
# outerDiv
{
top:0%;
left:0%;
position:absolute;
background-image:url('../img/FloatingPanel.png');//transperant image
color:White;
z-index: 1102;
Height:100%;
width:100%;
}
Give a higher Z-index for #divConfMessage than the Z-index of outerDiv(ie:1103).
Show the outerDiv onclick of btDelete