2016-03-01 77 views
0

我有一个数组在js中包含一些名称的复选框,我想设置检查。 问题是我不能做正确,我不知道为什么我错了 这是我的代码多选复选框设置检查html

var array = ['one','two word','three']; 
for(var i = 0; i < array.length;i++) 
$(':checkbox[value="'+array[i]+'"]').prop('checked', true); 

有了这个HTML

<input type="checkbox" name="one[]" value="two word"> 
<input type="checkbox" name="one[]" value="four"> 
<input type="checkbox" name="one[]" value="one"> 

有了这个代码我复选框保持uncheked,可有人告诉我为什么?

回答

1

True不是checked属性的有效属性值。该值可以被省略或必须checked

var array = ['one','two word','three']; 
 

 
for(var i = 0; i < array.length;i++) { 
 
    $(':checkbox[value="'+array[i]+'"]').prop('checked', 'checked'); 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<input type="checkbox" name="one[]" value="two word"> 
 
<input type="checkbox" name="one[]" value="four"> 
 
<input type="checkbox" name="one[]" value="one">

下面是来自W3C

https://www.w3.org/TR/1999/REC-html401-19991224/interact/forms.html#h-17.4

+0

问题仍然存在,这是复选框 [prevObject的控制台日志:n.fn .init [1],context:document,selector:“:checkbox [value =”Trieste“]]] context:documentlength:0prevObject:n.fn.init [1] selector:”:checkbox [value =“one”] “__proto__:n [0] – cristianbregant

+0

是这样吗?你可以在代码片段中运行代码吗? –

+0

是的,但在这一点上,我认为在别的地方可能会有问题。我现在要看看问题:D谢谢! – cristianbregant

0

它为我不同的是有三个一项规范为一个值而不是FOUR ..

我修改了y我们的代码,并得到了所有三个检查您可以设置一个值 http://www.w3schools.com/jsref/prop_checkbox_value.asp

<input type="checkbox" name="one[]" value="two word"> 
<input type="checkbox" name="one[]" value="four"> 
<input type="checkbox" name="one[]" value="one"> 

var array = ['one','two word','four']; 
for(var i = 0; i < array.length;i++) { 
$(':checkbox[value="'+array[i]+'"]').prop('checked', true); 
} 

这里是一个小提琴Sample fiddle