Javascript 如果所有复选框都具有相同的名称,如何验证复选框选择?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4436524/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 12:24:41  来源:igfitidea点击:

How to validate for checkbox selection if all checkbox have same name?

javascriptcheckbox

提问by OM The Eternity

Hi All I have a group of check box having same name so as to get the array of single variable when it is posted on serverside for exampleL

大家好我有一组具有相同名称的复选框,以便在服务器端发布时获取单个变量的数组,例如L

<input type="checkbox" name="midlevelusers[]" value="1">
<input type="checkbox" name="midlevelusers[]" value="1">
<input type="checkbox" name="midlevelusers[]" value="1">
<input type="checkbox" name="midlevelusers[]" value="1">

I need a javascript validation to check whether any checkbox is selected or not?

我需要一个 javascript 验证来检查是否选中了任何复选框?

Thanks and Regards

感谢致敬

NOTE: I need javascript validation

注意:我需要 javascript 验证

回答by T.J. Crowder

You can access the DOM elements and check their checkedproperty. For instance:

您可以访问 DOM 元素并检查它们的checked属性。例如:

var list, index, item, checkedCount;

checkedCount = 0;
list = document.getElementsByTagName('input');
for (index = 0; index < list.length; ++index) {
    item = list[index];
    if (item.getAttribute('type') === "checkbox"
        && item.checked
        && item.name === "midlevelusers[]") {
        ++checkedCount;
    }
 }

Live example

活生生的例子

There we're looking through the whole document, which may not be efficient. If you have a container around these (and presumably you do, a formelement), then you can give that element an ID and then look only within it (only the var, form =, and list =lines are new/different):

我们正在查看整个文档,这可能效率不高。如果你有这些周围的容器(可能你做什么,一个form元素),那么你可以给该元素的ID,然后看看只在它(只是varform =list =线新/不同):

var form, list, index, item, checkedCount;

checkedCount = 0;
form = document.getElementById('theForm');
list = form.getElementsByTagName('input');
for (index = 0; index < list.length; ++index) {
    item = list[index];
    if (item.getAttribute('type') === "checkbox"
        && item.checked
        && item.name === "midlevelusers[]") {
        ++checkedCount;
    }
 }

Live example

活生生的例子



Off-topic: You haven't mentioned using a library, so I haven't used one above, but FWIW this stuff is mucheasier if you use one like jQuery, Prototype, YUI, Closure, or any of several others. For instance, with jQuery:

题外话:你没有提到使用库,所以我没有在上面使用过,但是如果你使用像jQueryPrototypeYUIClosure其他几个库中的任何一个,FWIW 这些东西会容易得多。例如,使用 jQuery:

var checkedCount = $("input[type=checkbox][name^=midlevelusers]:checked").length;

Live exampleOther libraries will be similar, though the details will vary.

实时示例其他库将类似,但细节会有所不同。

回答by Bhanu Prakash Pandey

<form name="myform" method="POST" action="" onsubmit="return checkTheBox();">
  <input type="checkbox" name="midlevelusers[]" value="1" /> 1 &nbsp;&nbsp;
  <input type="checkbox" name="midlevelusers[]" value="2" /> 2 &nbsp;&nbsp;
  <input type="checkbox" name="midlevelusers[]" value="3" /> 3 &nbsp;&nbsp;
  <input type="checkbox" name="midlevelusers[]" value="4" /> 4 &nbsp;&nbsp;
  <input type="checkbox" name="midlevelusers[]" value="5" /> 5 &nbsp;&nbsp;
  <input type="submit" value="Submit Form" />
</form>

<script type="text/javascript">
  function checkTheBox() {
    var flag = 0;
    for (var i = 0; i< 5; i++) {
      if(document.myform["midlevelusers[]"][i].checked){
        flag ++;
      }
    }
    if (flag != 1) {
      alert ("You must check one and only one checkbox!");
      return false;
    }
    return true;
  }
</script>

回答by KooiInc

use id's

使用身

<input type="checkbox" name="midlevelusers[]" id="mlu1" value="1">
<input type="checkbox" name="midlevelusers[]" id="mlu2" value="2">
<input type="checkbox" name="midlevelusers[]" id="mlu3" value="3">
<input type="checkbox" name="midlevelusers[]" id="mlu4" value="4">

now you can do

现在你可以做

for (var i=1;i<5;i++){
  var el = document.getElementById('mlu'+i);
  if (el.checked) { /* do something */}
}

回答by Nik

try,

尝试,

function validate() {
    var chk = document.getElementsByName('midlevelusers[]')
    var len = chk.length

    for(i=0;i<len;i++)
    {
         if(chk[i].checked){
        return true;
          }
    }
    return false;
    }

回答by Matt Phillips

This function would alert whether or not a checkbox has any values checked.

此函数会提醒复选框是否选中了任何值。

function isChecked(checkboxarray){
    for (counter = 0; counter < checkboxarray.length; counter++){
        if (checkboxarray[counter].checked){
            alert("Checkbox has at least one checked");
        else{
            alert("None checked");
        }

You would need to add a bit more to do what you actually want to do with it but that will get you on the right track I think!

你需要添加更多的东西来做你真正想做的事情,但我认为这会让你走上正确的轨道!

回答by James111

You could use jQueryand do it this way:

你可以这样使用jQuery和做到这一点:

if($('input[name="light[]"]:checked').length < 1){
            alert("Please enter the light conditions");
}