SharpCoder
SharpCoder

Reputation: 19163

Selecting few checkboxes under a div using jquery by matching names with an array

 <div id="menu" class="dropdown-menu hold-on-click dropdown-checkboxes pull-right">
   <label><input type="checkbox" id="cbox0" data-column="0" name = '1'>1</label>
   <label><input type="checkbox" id="cbox0" data-column="0" name = "2'>2</label>
   <label><input type="checkbox" id="cbox0" data-column="0" name = '3'>3</label>
   <label><input type="checkbox" id="cbox0" data-column="0" name = '4'>4</label>
   <label><input type="checkbox" id="cbox0" data-column="0" name = '5'>5</label>
   <label><input type="checkbox" id="cbox0" data-column="0" name = '6'>6</label>
</div>

var columns = ['2','5','6'];

I want to set all the check-boxs whos name is present in columns array available under the a div to be checked using jQuery. I googled and found multiple solutions where user is checking all the check-box available under a div but my problem is all the checkboxes inside the div are placed under a label & i want to select only those columns whos name is present in columns array.

Please help.

Upvotes: 0

Views: 199

Answers (2)

Satpal
Satpal

Reputation: 133403

You can simply use

$('#menu').find(':checkbox').prop('checked', true);

Note: IDs must be unique.

var columns = ['2','5','6'];
$("#menu").find("input[type='checkbox']").filter(function(){
    return columns.indexOf($(this).attr('name')) > -1;
}).prop("checked",true);

DEMo

Upvotes: 2

Anoop Joshi P
Anoop Joshi P

Reputation: 25527

Use jquery attribute selector for this.

var columns = ['2','5','6'];
$.each( columns, function( key, value ) {
    $("#menu :checkbox[name='"+value+"']").prop("checked",true);
});

Fiddle

Upvotes: 1

Related Questions