我在div中有一组复选框。这是一个例子:
<input id="customer426693" name="customers" type="checkbox" class="filled-in form-check-input customerCheckbox customerRequired" value="426693">
我的javascript函数中还有一个要选择的值数组。是否有一种优雅的方法来选择使用jquery在数组中存在值的所有复选框?
感谢。
答案 0 :(得分:1)
这就是你想要的吗?
var selectedList = [3,4,6];
function MakeSelected() {
$("#checkBoxContainer").find("input").each(function(index,item){
if(selectedList.indexOf( $(item).data("customerid") )>=0)
$(item).prop("checked",true);
});
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<p>
I deleted class to make more readable.
</p>
<div id="checkBoxContainer">
<input id="customer1" type="checkbox" value="1" data-customerid="1" />1 <br>
<input id="customer2" type="checkbox" value="2" data-customerid="2" />2 <br>
<input id="customer3" type="checkbox" value="3" data-customerid="3" />3 <br>
<input id="customer4" type="checkbox" value="4" data-customerid="4" />4 <br>
<input id="customer5" type="checkbox" value="5" data-customerid="5" />5 <br>
<input id="customer6" type="checkbox" value="6" data-customerid="6" />6 <br>
</div>
<button type="button" onclick="MakeSelected()">try it!</button>
&#13;