jQuery-确保检查所有无线电组 [英] jQuery - ensuring all radio groups are checked

查看:105
本文介绍了jQuery-确保检查所有无线电组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用jQuery遍历多个(动态)单选按钮组,如果还没有做出选择,它将引发错误并停止表单提交.

I'd like to loop through multiple (dynamic) radio button groups using jQuery, and if any haven't had a selection made, it throws up an error and stops the form submission.

到目前为止,这是我的努力:

Here's my effort so far:

$("form").submit(function() {
    $(":radio").each(function(){
        if($(this).val().length == 0) {
            alert('Not selected all radios');
            return false;
        }
    }); 
});

但是总是会忽略if语句,该语句将停止提交,好像$(this)实际上不是单选按钮的值一样?

But it always ignores the if statement which will stop the submission, as if maybe $(this) isn't actually the value of the radio buttons?

这是一个jsFiddle: http://jsfiddle.net/aVVW9/

Here's a jsFiddle: http://jsfiddle.net/aVVW9/

任何帮助将不胜感激,谢谢!

Any help would be much appreciated, thank you!

推荐答案

尝试一下.方法是遍历所有单选按钮,然后使用:checked提取单选按钮组的名称,以查看是否检查了该组中的任何成员.找到第一个丢失的检查后,一个简单的布尔值将停止错误.

Try this. The approach is to loop through ALL radio buttons, and THEN extract the name of the radio button group, using :checked to see if any member of that group is checked. A simple Boolean stops the errors after the first missing check is found.

$("form").submit(function() {
    var submitme = true;
    $(':radio').each(function() { // loop through each radio button
        nam = $(this).attr('name'); // get the name of its set
        if (submitme && !$(':radio[name="'+nam+'"]:checked').length) { 
        // see if any button in the set is checked
            alert(nam+' group not checked');
            submitme = false;
        }
    });
    return submitme; // cancel the form submit
});        ​

http://jsfiddle.net/mblase75/aVVW9/5/

这篇关于jQuery-确保检查所有无线电组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆