JQuery - checking all radio groups

I would like to iterate over several (dynamic) switch groups using jQuery, and if someone had no choice, it throws an error and stops submitting the form.

Here are my efforts:

$("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 view, as if maybe $ (this) is not really the value of the switches?

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

Any help would be greatly appreciated, thanks!

+4
source share
3 answers

Try it. The approach is to scroll through ALL the radio buttons, and THEN retrieves the name of the switch group using :checked to check if any member of that group has been checked. A simple Boolean stops errors after detecting the first missing check.

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

+8
source
 $("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 in a div having the radio_group class and radio_group over them.

+1
source

I accidentally found an even more elegant solution! This is only useful when you know the exact number of switches.

 var x = 0; $(":radio").change(function() { x = x + 1; if (x == count) { //do smth } }); 
0
source

Source: https://habr.com/ru/post/1413812/


All Articles