如何设置同一行中的另一个字段值

how to set another field value in same row

本文关键字:字段 一行 另一个 何设置 设置      更新时间:2023-09-26

给定一个5列的网格和第2列的id数组,如何将第1列的布尔值设置为数组中的id的true ?有25行,其中5行在数组中。

var ProductIDArray = [2,5,9,12,16]; 
var i; 
for (i = 0; i < ProductIDArray.length; i++) {
    document.getElementById("chk").checked = true; 
}

第一个错误:你不能/不应该在页面上有重复的id。要么使用类,要么为每个元素设置唯一的id。

第二个错误:你需要在循环中每次检查不同的元素


基于此:

列1是一个复选框列。只有数组中的那些应该被选中。其他行不应该选中第1列。

让我们试着解决它。假设您的复选框ID是chk_N,其中N是与产品ID (chk_1, chk_2等…)相匹配的数字,代码应该如下所示:

var ProductIDArray = [2,5,9,12,16]; 
var i; 
for (i = 0; i < ProductIDArray.length; i++) {
    document.getElementById("chk_" + ProductIDArray[i]).checked = true; 
}

下面是一个例子:

var ProductIDArray = [2, 5, 9, 12, 16];
var i;
for (i = 0; i < ProductIDArray.length; i++) {
  document.getElementById("chk_" + ProductIDArray[i]).checked = true;
}
<input type="checkbox" id="chk_11" />11<br>
<input type="checkbox" id="chk_2" />2<br>
<input type="checkbox" id="chk_33" />33<br>
<input type="checkbox" id="chk_45" />45<br>
<input type="checkbox" id="chk_65" />65<br>
<input type="checkbox" id="chk_5" />5<br>
<input type="checkbox" id="chk_16" />16<br>
<input type="checkbox" id="chk_9" />9<br>
<input type="checkbox" id="chk_12" />12<br>
...