Akshat Tyagi Akshat Tyagi - 4 months ago 7
jQuery Question

jQuery to perform an action when all radiobuttons with a particular class have been checked

I have to develop a Question Template, which loads 3 questions on the page at a time. When the 3 questions have all been answered(with their radiobuttons selected), it moves on to the next section. Here is the code for the inputs:



<input type='radio' name='q_1' class='section_1' value=1 required>
<input type='radio' name='q_1' class='section_1' value=0.75 required>
<input type='radio' name='q_1' class='section_1' value=0.5 required>
<input type='radio' name='q_1' class='section_1' value=0.25 required>

<input type='radio' name='q_2' class='section_1' value=1 required>
<input type='radio' name='q_2' class='section_1' value=0.75 required>
<input type='radio' name='q_2' class='section_1' value=0.5 required>
<input type='radio' name='q_2' class='section_1' value=0.25 required>

<input type='radio' name='q_3' class='section_1' value=1 required>
<input type='radio' name='q_3' class='section_1' value=0.75 required>
<input type='radio' name='q_3' class='section_1' value=0.5 required>
<input type='radio' name='q_3' class='section_1' value=0.25 required>




I want to make sure that once a radiobutton with the name 'q_1', 'q_2' and 'q_3' is selected from 'section_1', we move to section two. How would I approach this problem with a simple jquery code?

Answer

You need to use the change event:

  • You can use :radio selector

  • $(':radio[name^="q_"].section_1') select all radios with class section_1 and name starting with q_ (so, in your case, q_1, q_2 and q_3).

  • change event because:

    ...radio buttons, the event is fired immediately when the user makes a selection....

  • test if all radios are checked: $(':radio[name^="q_"].section_1:checked').length == 3

$(function () {
  $(':radio[name^="q_"].section_1').on('change', function(e) {
    if ($(':radio[name^="q_"].section_1:checked').length == 3) {
      console.log('ALL required are checked!');
    }
  })
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type='radio' name='q_1' class='section_1' value=1 required>
<input type='radio' name='q_1' class='section_1' value=0.75 required>
<input type='radio' name='q_1' class='section_1' value=0.5 required>
<input type='radio' name='q_1' class='section_1' value=0.25 required>
<br>
<input type='radio' name='q_2' class='section_1' value=1 required>
<input type='radio' name='q_2' class='section_1' value=0.75 required>
<input type='radio' name='q_2' class='section_1' value=0.5 required>
<input type='radio' name='q_2' class='section_1' value=0.25 required>
<br>
<input type='radio' name='q_3' class='section_1' value=1 required>
<input type='radio' name='q_3' class='section_1' value=0.75 required>
<input type='radio' name='q_3' class='section_1' value=0.5 required>
<input type='radio' name='q_3' class='section_1' value=0.25 required>

Comments