I see plenty of methods to loop through and retrieve the values of the check boxes that are checked, I need to kick off a process with the checkbox value immediately when a checkbox is checked in the checkbox list. Not sure if it's possible, but would be nice if it is. Otherwise I'd have to create a extremely complex and inefficient procedure to check ALL check boxes and their relationship to values in the system, I'd like to avoid that. My code thus far:
I bind the data to the checkbox list in the code behind:
First I get the data from the database:
MyDataSet = GetItems(MyConnection, MyDataSetAssoc.Tables(0).Rows(0)("itemvalue"), MyDataSetPrograms.Tables(0).Rows(0)("Program"))
Then bind it to the control:
CheckBoxList_Items.DataSource = MyDataSet
CheckBoxList_Items.DataMember = "Items"
CheckBoxList_Items.DataTextField = "ItemName"
CheckBoxList_Items.DataValueField = "ItemID"
This is the jquery code in the document ready function:
$(document).ready(function() {
$('#<%= CheckBoxList_Items.ClientID %>').click(function() {
if ($(this).is(":checked")) {
alert("ID #" + this.value + " was just checked.");
} else {
alert("ID #" + this.value + " was just unchecked.");
}
});
});
This executes when any checkbox in the list is clicked, now I need to get the value of the checkbox that was just checked. this.value
is undefined and
only the else
portion of the if
statement is executed, so that won't do it. Is there a way I can get the value of the checkbox that just triggered this function? Or is there another approach I have to use? There can be 1 to N items in the list, and there are three checkbox lists I have to manipulate when one checkbox is "clicked" This particular checkboxlist is at the lowest "level" in the three.
There were a couple of problems with the system I'm working on. It's 20 years old and was initially developed under .NET 2.0 (I believe), it's now running under .NET 4.8. The code itself wasn't off by much, thanks to @barmar, I got the proper checkbox in the click function. The code now reads:
$(document).ready(function() {
$('#<%= CheckBoxList_Items.ClientID %> :checked').click(function() {
if ($(this).is(":checked")) {
alert("ID # " + $(this).val() + " was just checked.");
} else {
alert("ID # " + $(this).val() + " was just unchecked.");
}
});
});
Note the :checked
portion of the function declaration.
The $(this).val()
portion of the code was returning on
because the data portion of the checkboxlist control wasn't being rendered because in the web.config
file there was this setting: <pages controlRenderingCompatibilityVersion="3.5">
. I removed the controlRenderingCompatibilityVersion="3.5
portion of the tag and the checkboxlist data is now being rendered and $(this).val()
returns the data value of the checkbox in the list that is clicked.