0

我必须在一个组中选择许多复选框,如果我必须按用户提供类似 ["1","3","8"] 的列表并且我必须选择,那么现在有 10 个复选框的值属性设置为从 0 到 9值为 1 ,3 和 8 的复选框。如何完成?请回复 !!

4

5 回答 5

2
var arr = ['1','3','8'];
/* find all the checkbox input elements.
   set the 'checked' property */
$('input[type=checkbox]').prop('checked', function(){
    // return  true if the value is in the array, false if not
    return $.inArray(this.value, arr) > -1;
});

JS 小提琴演示

或者,使用filter()

var arr = ['1','3','8'];

$('input[type=checkbox]').filter(function(){
    return $.inArray(this.value, arr) > -1;
}).prop('checked',true);

JS 小提琴演示

但是,在设置属性之前首先取消选中任何已选中的复选框可能是值得的:

var arr = ['1','3','8'];

$('input[type=checkbox]').prop('checked',false).filter(function(){
    return $.inArray(this.value, arr) > -1;
}).prop('checked',true);

JS 小提琴演示

最后,因为valueaninput总是一个字符串,而 JavaScript 中的数字不必被引用,以允许数组中没有引用的数字(以防止健忘,如果没有别的):

var arr = ['1',3,'8'];

$('input[type=checkbox]').prop('checked',false).filter(function(){
    return $.inArray(this.value, arr.toString()) > -1;
}).prop('checked',true);

JS 小提琴演示

参考:

于 2013-07-09T09:01:59.120 回答
1

例如,对于值 8 :

<input type="checkbox" class="chk" name="myGroup[]" value="7" />
<input type="checkbox" class="chk" name="myGroup[]" value="8" />

<script>
  $(".chk[value='8']").prop("checked", true);
</script>
于 2013-07-09T08:59:29.420 回答
1

这是一种方法——给你的复选框一个通用的类,即“myCheckbox”。

使用 jQuery 遍历所有带有“myCheckbox”类的复选框,并将它们的值与用户提供的列表进行比较。如果有匹配项,请选中该复选框。

伪 jQuery 代码:

$('.myCheckbox').each(function() {
  // you would search the array here
  if ($(this).value == "1") {
    $(this).check();
  }
});
于 2013-07-09T09:00:44.960 回答
0

你可以试试这个——

var arr =  ["1","3","8"];
$(':checkbox').each(function(){
  if($.inArray(this.value,arr) > -1){
   $(this).prop('checked',true);
  }
}) 
于 2013-07-09T09:00:27.160 回答
0

这应该可以解决您的问题:

var setArr = ["1","3","8"];

$('.checkbox').each(function(i, j){
if(jQuery.inArray($(j).val(), setArr)!= -1){

$(j).attr('checked', 'checked');
}

});

小提琴

于 2013-07-09T09:13:48.223 回答