当输入name[]时,JS对复选框的验证不起作用

JS validation for checkbox not working when put name []

本文关键字:复选框 验证 不起作用 JS name 输入      更新时间:2023-09-26

我有一个JS验证复选框。

function ActionCcdCheck (theForm)
{
    if (theForm.ccd_chk.checked)
    {
        theForm.ccd_pos[0].className = 'part';
        theForm.ccd_pos[1].className = 'part';
        theForm.ccd_pos[2].className = 'part';
        theForm.ccd_pos[0].disabled  = false;
        theForm.ccd_pos[0].checked  = false;
        theForm.ccd_pos[1].disabled  = false;
        theForm.ccd_pos[1].checked  = false;
        theForm.ccd_pos[2].disabled  = false;
        theForm.ccd_pos[2].checked  = false;
    }
    else
    {
        theForm.ccd_pos[0].disabled  = true;
        theForm.ccd_pos[1].disabled  = true;
        theForm.ccd_pos[2].disabled  = true;
    }
}

的复选框
<td colspan="1" rowspan="2" width="35">CCD</td>
<td>Check</td>
<td><input type="checkbox" name="ccd_chk" value="yes" class="part" onclick="ActionCcdCheck (this.form);" onkeypress="FocusChange (this.form, 5, 4);"/> Yes</td>
<tr>
<td>Position</td>
<td>
<input type="checkbox" name="ccd_pos[]" value="front" class="part" onkeypress="FocusChange (this.form, 6, 3);"/> Front
<input type="checkbox" name="ccd_pos[]" value="back" class="part" onkeypress="FocusChange (this.form, 7, 2);"/> Back
<input type="checkbox" name="ccd_pos[]" value="fb" class="part" onkeypress="FocusChange (this.form, 8, 1);"/> FB
</td>
<tr>

现在我面临的问题,当我把复选框的名称像这样的名称="ccd_pos[]"。JS验证不起作用。我用它是因为我想提交多个checkbox的值

所以谁能给我一个建议?谢谢。

在你的代码中:

theForm.ccd_pos[0]

正在寻找形式的ccd_pos属性,没有一个。您需要的是如下内容:

theForm['ccd_pos[]'][0]

作为具有相同名称的表单控件将作为集合返回,因此:

theForm['ccd_pos[]']

返回名称为ccd_pos[]的三个控件的集合。然后使用普通索引名访问集合的各个成员。

请注意,在javascript中,点表示法是正式属性访问的快捷方式,只能在名称符合标识符规则的情况下使用。否则,必须使用方括号(正式)符号。

所以你的代码可以是这样的:
var box, boxes = theForm.['ccd_pos[]'];
for (var i=0, iLen=boxes.length; i<iLen; i++) {
  box = boxes[i];
  if (theForm.ccd_chk.checked) {
    box.className = 'part';
    box.disabled  = false;
    box.checked   = false;
  } else {
    box.disabled  = true;
    // and probably
    box.className = '';
  }
}