jQuery - ensuring all radio groups are checked

前端 未结 3 753
深忆病人
深忆病人 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:21

    $("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.

提交回复
热议问题