jQuery - ensuring all radio groups are checked

▼魔方 西西 提交于 2019-12-19 19:40:33

问题


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;
        }
    }); 
});

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?

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

Any help would be much appreciated, thank you!


回答1:


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/




回答2:


$("form").submit(function() {
    $(":radio", this).each(function(){
        if(!this.checked) {
            alert('Not selected all radios');
            return false;
        }
    }); 
});

or

$("form").submit(function() {
    if($(':radio:not(:checked)', this).length) {
       alert('Not selected all radios');
       return false;
    }
});

Check this demo. Here for simplicity I wrap each radio group within a div having class radio_group and loop over them.




回答3:


I've accidentally just found even more elegant solution! It is only useful when you know the exact count of radio buttons.

var x = 0;

$(":radio").change(function() {
x = x + 1;

if (x == count) {

//do smth

}

});


来源:https://stackoverflow.com/questions/10706925/jquery-ensuring-all-radio-groups-are-checked

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!