在多个复选框上更改checked属性

时间:2011-08-26 19:37:09

标签: jquery checkbox

我想使用jQuery设置checked属性

如何做到这一点?

 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"/>

我想在复选框中找到arr eq值...

           <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"/>

6 个答案:

答案 0 :(得分:4)

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

演示:http://jsfiddle.net/vfXZy/

答案 1 :(得分:1)

我认为你正在寻找这个基本上读取数组值并检查复选框的相应值。

var $input = $("input");
$.each(arr, function(){
   $input.filter("[value='"+this+"']").attr("checked", true);
});

在上面的代码中,它只找到input元素,只有一个ans存储在局部变量中,而在循环中它只是过滤,这样就不必每次都找到元素。

答案 2 :(得分:1)

试试这个:

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

答案 3 :(得分:1)

试试这个:

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

小提琴:http://jsfiddle.net/ZkMsD/

答案 4 :(得分:0)

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

JSFiddle Example

答案 5 :(得分:0)

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