I am returning a JSON data structure that I split and populate my array like so:
var arrayValues = data.contents.split('|');
// arrayValues = 1,3,4
How can I check the corresponding checkboxes based on the array values?
My HTML looks like this:
<div id="divID">
<input type="checkbox" name="test" value="1" /> Test 1<br />
<input type="checkbox" name="test" value="2" /> Test 2<br />
<input type="checkbox" name="test" value="3" /> Test 3<br />
<input type="checkbox" name="test" value="4" /> Test 4<br />
<input type="checkbox" name="test" value="5" /> Test 5<br />
</div>
Note: Unlike other input controls, a checkbox's value is only included in the submitted data if the checkbox is currently checked . If it is, then the value of the checkbox's value attribute is reported as the input's value.
The Input Checkbox defaultChecked property in HTML is used to return the default value of checked attribute. It has a boolean value which returns true if the checkbox is checked by default, otherwise returns false.
Try this using attribute selector
$.each(arrayValues, function(i, val){
$("input[value='" + val + "']").prop('checked', true);
});
Javascript
$.each(arrayValues, function (index, value) {
$('input[name="test"][value="' + value.toString() + '"]').prop("checked", true);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With