繁体   English   中英

如果它的值在数组中,如何设置选中的复选框

[英]How set checked checkbox if it's value is in array

我有输入:

  <div id="my">
   <input type="checkbox" value="1" name="names[]">
   <input type="checkbox" value="2" name="names[]">
   <input type="checkbox" value="3" name="names[]">
   <input type="checkbox" value="4" name="names[]">
  </div>

还有我的 javascript:

initValues=[1,2,3];
$('#my').find(':checkbox[name="names[]"]').each(function () {
  $(this).prop("checked", ($.inArray($(this).val(), initValues)));
});

现在我所有的复选框都被选中了。 我必须如何更改我的代码以设置检查 ckeckboxes 哪些值在 initValues 数组中?

$.inArray 返回索引,而不是布尔值。 另外, parseInt 你的值,因为当你拿起它时它被认为是字符串。

initValues=[1,2,3];
            $('#my').find(':checkbox[name="names[]"]').each(function () {
              $(this).prop("checked", $.inArray(parseInt($(this).val()), initValues) == -1 ? false : true );
            });

 let initValues = [1, 2, 3]; $('#my').find(':checkbox[name="names[]"]').each(function() { if (initValues.some(v => v == $(this).val())) { $(this).prop('checked', true); } });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="my"> <input type="checkbox" value="1" name="names[]"> <input type="checkbox" value="2" name="names[]"> <input type="checkbox" value="3" name="names[]"> <input type="checkbox" value="4" name="names[]"> </div>

您需要将该值转回一个数字,以便与数组值进行比较。

$.inArray(+$(this).val(), initValues))

修改示例:

 initValues=[1,2,3]; $('#my').find(':checkbox[name="names[]"]').each(function () { $(this).prop("checked", ($.inArray(+$(this).val(), initValues)) != -1); });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div id="my"> <input type="checkbox" value="1" name="names[]"> <input type="checkbox" value="2" name="names[]"> <input type="checkbox" value="3" name="names[]"> <input type="checkbox" value="4" name="names[]"> </div>

函数 printChecked(isChecked, value) { const newProjectStages = projectstage.filter((p) => p !== value);

if (isChecked) {
  newProjectStages.push(value);
}

Setprojectstage(newProjectStages);

var items = document.getElementsByName("tr");
var selectedItems = [];
for (var i = 0; i < items.length; i++) {
  if (items[i].type == "checkbox" && items[i].checked == true)
    selectedItems.push(items[i].value);
}
console.log("selected val", selectedItems);
Setselectedprostages(selectedItems);

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM