cherry
cherry

Reputation: 21

altering the checked property on multiple checkboxes

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

Answers (6)

aziz punjani
aziz punjani

Reputation: 25776

    var check_checkboxes = [1,2,5]; 
    $.each( check_checkboxes, function( index, value ){
        $('input:checkbox[value="'+ value +'"]').attr('checked', true ); 
    });

Upvotes: 0

ShankarSangoli
ShankarSangoli

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

Brian Glaz
Brian Glaz

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

Paul
Paul

Reputation: 141829

var $cbs = $('input:checkbox');
$.each([1,2,3], function(){
    $cbs.filter('[value="'+this+'"]').prop('checked', true);   
})

JSFiddle Example

Upvotes: 0

Matt Bradley
Matt Bradley

Reputation: 4495

Try this:

for (var i in arr)
    $('input[value="' + arr[i] + '"]').prop('checked', true);

Fiddle: http://jsfiddle.net/ZkMsD/

Upvotes: 1

Dennis
Dennis

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

Related Questions