Diego
Diego

Reputation: 591

Getting the value of a selected radio button doesn't work right

I'm making a quiz and with pure JS everything is working fine but for consistency I would like to do it with jQuery, but jQuery is always looking for the first value of the radio options, not for the selected option. What could be the work around with jQuery?

HTML

<form id='quiz'>
    <input type='radio' class='mc' name='q1' value='a1'>Answer 1<br>
    <input type='radio' class='mc' name='q1' value='a2'>Answer 2 <!-- Selected option -->
</form>

JS

var a1 = document.quiz.q1.value;
alert(a1) // output is: a2

var a1 = $('#quiz').find('input[name="q1"]').val();
alert(a1) // output is: a1

Upvotes: 0

Views: 45

Answers (1)

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167162

That's the usual jQuery (or JavaScript) behaviour to get the first value and not the selected option's value. You have to use :checked when using jQuery:

$(function () {
  var a = $('#quiz').find('input[name="q1"]:checked').val();
  console.log(a);
  $("button").click(function () {
    var a = $('#quiz').find('input[name="q1"]:checked').val();
    console.log(a);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id='quiz'>
  <label><input type='radio' class='mc' name='q1' value='a1'>Answer 1</label><br>
  <label><input type='radio' class='mc' name='q1' value='a2' checked="checked">Answer 2 </label><!-- Selected option -->
</form>

<button>Check Selected</button>

In the above snippet, try to select something and click the button to see what's selected value. Also, by default, I have checked the second answer. :) Hope this helps.

Upvotes: 2

Related Questions