Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check checkboxes based on values?

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>
like image 677
Paul Avatar asked Nov 29 '11 18:11

Paul


People also ask

Does checkbox have value attribute?

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.

What is the value of checkbox when checked?

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.


2 Answers

Try this using attribute selector

$.each(arrayValues, function(i, val){

   $("input[value='" + val + "']").prop('checked', true);

});
like image 122
ShankarSangoli Avatar answered Nov 03 '22 22:11

ShankarSangoli


Javascript

$.each(arrayValues, function (index, value) {
  $('input[name="test"][value="' + value.toString() + '"]').prop("checked", true);
});
like image 29
John Hartsock Avatar answered Nov 03 '22 21:11

John Hartsock