Get unique value from mutiple forms that have radio buttons – jQuery

Tips

  • make sure all your elements have unique ids
  • wrap the radio buttons with the labels, it is easier and cleaner
  • use event delegation, by assigning the event handler at the div level, rather than to every radio button
  • you can probably use a single form element

$('#trivia').on('click', e => {
  let div = $("#trivia");
  let rbs = div.find('input[type="radio"][value="correct"]');
  let rbsChecked = 0;
  $(rbs).each((i, e) => {
    if (e.checked)
      rbsChecked++;
  });
  $("#score").text(rbsChecked + "/" + rbs.length);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="trivia">
  <form class='card0'>
    <text>Question</text>
    <label><input type="radio" id="Answer0" value="correct" name="question0">Answer</label>
    <label><input type="radio" id="Wrong0" value="incorrect" name="question0">Wrong</label>
  </form>
  <form class='card1'>
    <text>Question</text>
    <label><input type="radio" id="Answer1" value="correct" name="question1">Answer</label>
    <label><input type="radio" id="Wrong1" value="incorrect" name="question1">Wrong</label>
  </form>
</div>
<output id="score"></output>

Good luck

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top