mathlearner
mathlearner

Reputation: 7639

Selecting multiple check boxes in a group using jQuery

i have to select many checkboxes in a group there are 10 checkboxes with value attribute set from 0 to 9 now if i have to provide a list like ["1","3","8"] by user and i have to select checkbox with value 1 ,3 and 8.How to accomplsh?? please reply !!

Upvotes: 0

Views: 226

Answers (5)

David Thomas
David Thomas

Reputation: 253318

var arr = ['1','3','8'];
/* find all the checkbox input elements.
   set the 'checked' property */
$('input[type=checkbox]').prop('checked', function(){
    // return  true if the value is in the array, false if not
    return $.inArray(this.value, arr) > -1;
});

JS Fiddle demo.

Or, using filter():

var arr = ['1','3','8'];

$('input[type=checkbox]').filter(function(){
    return $.inArray(this.value, arr) > -1;
}).prop('checked',true);

JS Fiddle demo.

It might be worth, however, first unchecking any already-checked checkboxes before you set the property:

var arr = ['1','3','8'];

$('input[type=checkbox]').prop('checked',false).filter(function(){
    return $.inArray(this.value, arr) > -1;
}).prop('checked',true);

JS Fiddle demo.

Finally, because the value of an input is always a string, whereas numbers in JavaScript don't have to be quoted, to allow for unquoted numbers in the array (to guard against forgetfulness, if nothing else):

var arr = ['1',3,'8'];

$('input[type=checkbox]').prop('checked',false).filter(function(){
    return $.inArray(this.value, arr.toString()) > -1;
}).prop('checked',true);

JS Fiddle demo.

References:

Upvotes: 2

RONE
RONE

Reputation: 5485

This should fix your issue:

var setArr = ["1","3","8"];

$('.checkbox').each(function(i, j){
if(jQuery.inArray($(j).val(), setArr)!= -1){

$(j).attr('checked', 'checked');
}

});

FIDDLE

Upvotes: 0

James
James

Reputation: 13501

This is one way to do it - give your checkboxes a common class, i.e. "myCheckbox".

Use jQuery to iterate through all the checkboxes with the class "myCheckbox", and compare their value with the list provided by the user. If there's a match, select the checkbox.

Pseudo jQuery code:

$('.myCheckbox').each(function() {
  // you would search the array here
  if ($(this).value == "1") {
    $(this).check();
  }
});

Upvotes: 1

Adil Shaikh
Adil Shaikh

Reputation: 44740

You can try this -

var arr =  ["1","3","8"];
$(':checkbox').each(function(){
  if($.inArray(this.value,arr) > -1){
   $(this).prop('checked',true);
  }
}) 

Upvotes: 0

Pouki
Pouki

Reputation: 1664

By example, for the value 8 :

<input type="checkbox" class="chk" name="myGroup[]" value="7" />
<input type="checkbox" class="chk" name="myGroup[]" value="8" />

<script>
  $(".chk[value='8']").prop("checked", true);
</script>

Upvotes: 1

Related Questions