Reputation: 1
I am working on a script for setting checkboxes according to values stored in an array (part of a larger script for allowing the user to revert a form to its initial values). The code is basically this:
$("#myForm :checkbox[name='myName[]']").each(function(){
if($.inArray($(this).val(),initValues)!=-1){
$(this).prop("checked",true);
} else {
$(this).prop("checked",false);
}
});
initValues contains the value attributes of the boxes that were initially checked.
The script checks the first element in $("#myForm :checkbox[name='myName[]']")
but subsequent elements all appear to be unchecked. Firebug shows that the checked
attribute is being changed but the box itself is unchecked.
I have tried verious permutations of attr()
in place of prop()
all with the same results, and the script behaves the same way in Firefox 11.0 and Chrome 18.0 on OS X.
Upvotes: 0
Views: 6519
Reputation: 1048
There is another way. If you give each of your checkboxes the same class, you can actually just pass an array into .val for the class.
jQuery(".nameInput").val(initValues);
It's simple, elegant, and works
Upvotes: 2
Reputation: 14122
html attributes can be messup if not set as string.
I suggest replacing:
$(this).prop("checked",true);
by
$(this).prop("checked","checked");
or
$(this).prop("checked",false);
by
$(this).prop("checked","");
Upvotes: 0
Reputation: 8552
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
var initValues = ['eee', 'mec', 'csc'];
$('#btnResetCheckBox').click(function () {
$('#myForm').find(':checkbox[name^="myName"]').each(function () {
$(this).prop("checked", ($.inArray($(this).val(), initValues) != -1));
});
//Or
// $('#myForm').find(':checkbox[name^="myName"]').prop('checked', false);
// $.each(initValues, function (i, val) {
// $('#myForm').find(':checkbox[name^="myName"][value="' + val + '"]').prop("checked", true);
// });
});
$('#btnResetCheckBox').trigger('click');
});
</script>
</head>
<body>
<form id="myForm" action="">
<div>
<input type="checkbox" name="myName[1]" value="eee" />eee<br />
<input type="checkbox" name="myName[2]" value="ece" />ese<br />
<input type="checkbox" name="myName[3]" value="it" />it<br />
<input type="checkbox" name="myName[4]" value="csc" />csc<br />
<input type="checkbox" name="myName[5]" value="mec" />mec<br />
</div>
<input type="button" id="btnResetCheckBox" value="Reset Check Box" />
</form>
</body>
</html>
Upvotes: 2