簡體   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