jQuery - ensuring all radio groups are checked

前端 未结 3 737
深忆病人
深忆病人 2021-01-18 09:34

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.

3条回答
  •  旧巷少年郎
    2021-01-18 10:31

    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/

提交回复
热议问题