开发者

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开发者_JAVA百科="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"/>


for (var count = 0; count < arr.length; count++) {
    $("input[type='checkbox'][value='" + arr[count] + "']").attr("checked", true);
}

Demo: http://jsfiddle.net/vfXZy/


Try this:

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

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


try this:

<script type="text/javascript">
for(var i=0; i<arr.length; i++) {
    $('input[value=' + arr[i] + ']').attr('checked','checked');
}
</script>


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.


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

JSFiddle Example


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜