Reputation: 21
I want to use jQuery to set the checked
attribute
How can this be done?
var arr = new Array(1, 2, 3);
<input type="checkbox" name="chk" value="1"/>
<input type="checkbox" name="chk" value="2"/>
<input type="checkbox" name="chk" value="3"/>
<input type="checkbox" name="chk" value="4"/>
<input type="checkbox" name="chk" value="5"/>
<input type="checkbox" name="chk" value="6"/>
<input type="checkbox" name="chk" value="7"/>
i want to found arr eq value in checkbox...
<input type="checkbox" name="chk" value="1" checked/>
<input type="checkbox" name="chk" value="2" checked/>
<input type="checkbox" name="chk" value="3" checked/>
<input type="checkbox" name="chk" value="4"/>
<input type="checkbox" name="chk" value="5"/>
<input type="checkbox" name="chk" value="6"/>
<input type="checkbox" name="chk" value="7"/>
Upvotes: 2
Views: 2499
Reputation: 25776
var check_checkboxes = [1,2,5];
$.each( check_checkboxes, function( index, value ){
$('input:checkbox[value="'+ value +'"]').attr('checked', true );
});
Upvotes: 0
Reputation: 69905
I think you are looking for this which basically reads the array values and checks checkbox with corresponding value.
var $input = $("input");
$.each(arr, function(){
$input.filter("[value='"+this+"']").attr("checked", true);
});
In the above code it finds input
elements only once ans stores in a local variable and in the loop it just filters so that way it doesn't have to find the element everytime.
Upvotes: 1
Reputation: 15676
try this:
<script type="text/javascript">
for(var i=0; i<arr.length; i++) {
$('input[value=' + arr[i] + ']').attr('checked','checked');
}
</script>
Upvotes: 1
Reputation: 141829
var $cbs = $('input:checkbox');
$.each([1,2,3], function(){
$cbs.filter('[value="'+this+'"]').prop('checked', true);
})
Upvotes: 0
Reputation: 4495
Try this:
for (var i in arr)
$('input[value="' + arr[i] + '"]').prop('checked', true);
Fiddle: http://jsfiddle.net/ZkMsD/
Upvotes: 1
Reputation: 32598
for (var count = 0; count < arr.length; count++) {
$("input[type='checkbox'][value='" + arr[count] + "']").attr("checked", true);
}
Demo: http://jsfiddle.net/vfXZy/
Upvotes: 4