javascript 循环遍历具有一个元素的复选框数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13298744/
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-10-26 18:20:54  来源:igfitidea点击:

Looping through a checkbox array that has one element

javascriptformscheckbox

提问by Kenro

I have a list of dynamically created checkboxes named "tags" which I loop through with javascript to make sure only 1 is checked and to get the value. If for some reason this list of checkboxes only has 1 item, my script won't look at it. When I alert the tag's length I get undefined.

我有一个名为“标签”的动态创建的复选框列表,我使用 javascript 遍历这些复选框以确保只选中 1 个并获取值。如果由于某种原因,这个复选框列表只有 1 个项目,我的脚本将不会查看它。当我提醒标签的长度时,我会不确定。

    var total=[];
    for (var i=0; i < document.form1.tags.length; i++){
        if(document.form1.tags[i].checked==true){
            total.push(document.form1.tags[i].value);
        }
    }

    if(total.length==0){
        alert("Please select a product to edit.");
    }else if (total.length>1){
        alert("Please select only one product to edit.");
    }else{
        document.location = "go somewhere";
    }

采纳答案by Eli Gassert

Two suggestions:

两个建议:

  1. use getElementsByNameinstead to get all the elements so you can iterate them:

  2. Use a framework like jquery. Any reason you can't use jquery or another framework? Your life would be so much easier.

  1. 使用getElementsByName代替来获取所有元素,以便您可以迭代它们:

  2. 使用像 jquery 这样的框架。有什么理由不能使用 jquery 或其他框架?你的生活会轻松很多。

var tags = document.getElementsByName('tags');
for(var i = 0; i < tags.length; ++i)
{
    if(tags[i].checked) .....
}

回答by nirazul

Why do you need Checkboxes? Wouldn't this be a great opportunity to use Radiobuttons?

为什么需要复选框?这难道不是一个使用Radiobuttons的好机会吗?

回答by Kevin Boucher

You want radio buttons.

你想要单选按钮。

<input type='radio' name='tags' value='[whatever]' />

You won't have to 'check and make sure only one is selected'. And to get the

您不必“检查并确保只选择一个”。并获得

var tags = document.getElementsByName('tags'),
    value = '', i = 0;

for( ; i < tags.length; i++ )
{
    if( tags[i].checked ) {
        value = tags[i].value;
        break;
    }
}

回答by bas

from the top of my head... if there is only one checkbox selected it might be document.form1.tags is not an array...

从我的头顶......如果只选择了一个复选框,它可能是 document.form1.tags 不是一个数组......