javascript - 如何验证多个单选按钮

标签 javascript jquery radio-button

如何验证多个单选按钮。所有这些单选按钮都是动态生成的。

<input type="radio"  name="answer_option1" value="1" id="ans_options1" />
<input type="radio"  name="answer_option1" value="2" id="ans_options2" />
<input type="radio"  name="answer_option1" value="3" id="ans_options3" />
<input type="radio"  name="answer_option1" value="4" id="ans_options4" />

<input type="radio"  name="answer_option2" value="5" id="ans_options5" />
<input type="radio"  name="answer_option2" value="6" id="ans_options6" />
<input type="radio"  name="answer_option2" value="7" id="ans_options7" />
<input type="radio"  name="answer_option2" value="8" id="ans_options8" />

<input type="radio"  name="answer_option3" value="9" id="ans_options9" />
<input type="radio"  name="answer_option3" value="10" id="ans_options10" />
<input type="radio"  name="answer_option3" value="11" id="ans_options11" />
<input type="radio"  name="answer_option3" value="12" id="ans_options12" />

<input type="radio"  name="answer_option4" value="13" id="ans_options13" />
<input type="radio"  name="answer_option4" value="14" id="ans_options14" />
<input type="radio"  name="answer_option4" value="15" id="ans_options15" />
<input type="radio"  name="answer_option4" value="16" id="ans_options16" />

最佳答案

试试这个 http://jsfiddle.net/aamir/r9qR2/

由于每个组都有不同的名称属性,因此您必须对每组单选按钮进行验证。

if($('input[name="answer_option1"]:checked').length === 0) {
     alert('Please select one option');
}

如果您有无限数量的组。试试这个 http://jsfiddle.net/aamir/r9qR2/2/

    //Make groups
    var names = []
    $('input:radio').each(function () {
        var rname = $(this).attr('name');
        if ($.inArray(rname, names) === -1) names.push(rname);
    });

    //do validation for each group
    $.each(names, function (i, name) {
        if ($('input[name="' + name + '"]:checked').length === 0) {
            console.log('Please check ' + name);
        }
    });

如果您只想为所有组显示 1 个错误。试试这个 http://jsfiddle.net/aamir/r9qR2/224/

关于javascript - 如何验证多个单选按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20609863/

相关文章:

javascript - NestJS:设置@Body()的类型

javascript - 从 each() 返回不停止函数

javascript - 如何在几个 div 中迭代切换元素

javascript - 使用 Response.Write JSON 输出从 Jquery 调用 c# asmx Web 服务

javascript - 根据子项的数据属性删除 <li> 元素

JQuery - 按值查找单选按钮

c# - 设置 RadioButton 的值属性

jquery - 缓存 jQuery 对象 - 单选按钮

JavaScript:我可以获得完整的 url,包括域名、文件名和协议(protocol)吗?

javascript - 如何使用JQuery将html标签作为字符串内容的一部分输出到div