jquery get all changed checkboxes
I have a large number of checkboxes on the page each in a separate cell and I need to retrieve all of the checkboxes that have had their value changed since the original.
I am storing the original value in an attribute called "data-original-value" in a span that contains the checkbox, the span was added by asp.net when I added the attribute to the Attributes collection.
void Grid_ItemDataBound(object sender, GridItemEventArgs e)
{
var checkBoxControls = e.Item.Controls.All().OfType<CheckBox>();
foreach (var checkBox in checkBoxControls)
{
checkBox.Attributes["data-original-value"] = checkBox.Checked.ToString();
}
}
The output html looks something like the following:
<td>
<span data-original-value="True">
<i开发者_如何学JAVAnput id="ctl00_MainContent_ControlLandMatrixControl_grid_ctl00_ctl04_ctl01" type="checkbox" checked="checked" name="ctl00$MainContent$ControlLandMatrixControl$grid$ctl00$ctl04$ctl01">
</span>
</td>
I am using the following JQuery code to try and identify all of the checkbvoxes that have changed but it seems to be returning all checkboxes even those that haven't changed.
var checkBoxes = $(":checkbox").filter(function () { return $(this).checked != $(this).parent().attr("data-original-value"); });
I believe I am missing something with the comparison but I'm not entirely sure javascript/jquery isnt my fortay.
You don't need to re-invent the wheel, there is a predefined property defaultChecked for checkboxes, compare it with the checked-property.
$(':checkbox').filter(function ()
{
return ($(this).prop('checked')
!=
$(this).prop('defaultChecked'));
});
This may be interesting to you: Override the form 'Reset' behavior when data is refreshed via ajax
Please note: in jQuery <1.6 use this.checked != this.defaultChecked
, it will not work using $.attr()
you are comparing a string to a bool, convert the string to a bool using something like
var myBool = Boolean("false"); // == true
var myBool = !!"false"; // == true
You are comparing checkbox checked value which is a boolean against a string value which is True
so the filter will not return anything. Try this
var checkBoxes = $(":checkbox").filter(function () {
return $(this).checked.toString() != $(this).parent().attr("data-original-value").toLowerCase();
});
This might help....
var inputs = document.getElementsByTagName("input"); //or document.forms[0].elements;
var cbs = []; //will contain all checkboxes
var checked = []; //will contain all checked checkboxes
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].type == "checkbox") {
cbs.push(inputs[i]);
if (inputs[i].checked) {
checked.push(inputs[i]);
}
}
}
var nbCbs = cbs.length; //number of checkboxes
var nbChecked = checked.length; //number of checked checkboxes
精彩评论