Paul
Paul

Reputation: 11756

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>

Upvotes: 22

Views: 54223

Answers (5)

John Hartsock
John Hartsock

Reputation: 86902

Javascript

$.each(arrayValues, function (index, value) {
  $('input[name="test"][value="' + value.toString() + '"]').prop("checked", true);
});

Upvotes: 16

Christophe Quintard
Christophe Quintard

Reputation: 2743

Simpler :

$('input[name="test"]').val(arrayValues);

This will check the values from the array and deselect the others.

From the JQuery's doc : http://api.jquery.com/val/

val() allows you to pass an array of element values. This is useful when working on a jQuery object containing elements like <input type="checkbox">, <input type="radio">, and <option>s inside of a <select>. In this case, the inputs and the options having a value that matches one of the elements of the array will be checked or selected while those having a value that doesn't match one of the elements of the array will be unchecked or unselected, depending on the type.

Upvotes: 3

ShankarSangoli
ShankarSangoli

Reputation: 69915

Try this using attribute selector

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

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

});

Upvotes: 31

Smamatti
Smamatti

Reputation: 3931

Okay took me a moment to sort out my error in the code. I guess this question is answered by ShankarSangoli now.

I hope you don't mind me posting my solution either way. I'm just curious if this is worse for performance etc.

var arrayValues = new Array(1,3,4);

$('#divID input').filter(function(){
    return ($.inArray( parseInt($(this).attr('value')), arrayValues)) != -1;
}).attr('checked', 'checked');

Upvotes: 1

JohnP
JohnP

Reputation: 50029

You can loop through your array and do an attribute search on jQuery

var i = 0;
while (arrayValues.length < i) {
  var val = arrayValues[i];
  $('#divID input[value="' + val + '"]').prop('checked', 'checked');
  i++;
}

docs : http://api.jquery.com/attribute-equals-selector/

Upvotes: 2

Related Questions