数组复选框.检查javascript不工作

array checkbox.checked javascript not working

本文关键字:工作 javascript 检查 复选框 数组      更新时间:2023-09-26
<form id="form1" name="form_check" method="post" action="">
<p align="center">
<input type="checkbox" name="role[]" value="1">
<input type="checkbox" name="role[]" value="2">
<input type="checkbox" name="role[]" value="3"></p> 
<input type="submit" name="Submit" onclick="check_all()">
<script>
function check_all(){
    checkedBox="x"
    for(var i=0;i<document.getElementsByName('role[]').length;i++){
        if(document.getElementsByName('role[i]').checked == true){
            checkedBox="y"
            break // No need to check the rest since only one can be checked.
        }
    }
    if(checkBox == "x"){
        alert("Checkbox not checked")
    }
}
</script>
我已经写了上面的代码来检查复选框是否被选中。它不执行JavaScript区域中的if语句。我无法得到输出。当我试图执行这个脚本时,我得到这个错误:
{"error": "Shell form does not validate{'html_initial_name': u'initial-js_lib', 'form': <mooshell.forms.ShellForm object at 0x22c58d0>, 'html_name': 'js_lib', 'html_initial_id': u'initial-id_js_lib', 'label': u'Js lib', 'field': <django.forms.models.ModelChoiceField object at 0x25563d0>, 'help_text': '', 'name': 'js_lib'}{'html_initial_name': u'initial-js_wrap', 'form': <mooshell.forms.ShellForm object at 0x22c58d0>, 'html_name': 'js_wrap', 'html_initial_id': u'initial-id_js_wrap', 'label': u'Js wrap', 'field': <django.forms.fields.TypedChoiceField object at 0x2556cd0>, 'help_text': '', 'name': 'js_wrap'}"}

这个脚本为我工作:

var radios = document.getElementsByName('role[]');
checkedBox = "x";
for (i = 0; i < radios.length; i++) {
    if (radios[i].checked) {
        //alert("checked: " + radios[i].value);
        checkedBox = "y";
        break; // No need to check the rest since only one can be checked.
    }
}
  • 您声明了一个变量checkedBox,但在if条件下您使用的是checkBox

  • document.getElementsByName('role[i]')将为空,因为没有匹配的元素。( document.getElementsByName('role[' + i + ']')也将为null,原因相同。)

你真正需要使用的是

document.getElementsByName('role[]')[i].checked.

但是像这样在循环中访问DOM不是一个好的做法,最好将htmlCollection存储在一个变量中。

所以你的代码应该看起来像
function check_all() {
 checkedBox = "x";
 var checkboxes = document.getElementsByName('role[]');
 for (var i = 0; i < checkboxes.length; i++) {
    if ( checkboxes[i].checked) {
        checkedBox = "y"
        break // No need to check the rest since only one can be checked.
    }
 }
 if (checkedBox == "x") {
    alert("Checkbox not checked");
    return false;
 }
}

JSFiddle

指出:

  • 恕我直言,使用boolean值作为标志比x, y等更好的可读性和可理解性是一个很好的做法…
  • 您没有关闭共享代码中的<form>标签…

我想你会希望i不是一个文字I:

if(document.getElementsByName('role[' + i + ']').checked == true){

您总是可以使用console.log作为调试辅助来查找这些类型的错误。