Matthew G. Matthew G. - 4 months ago 8
HTML Question

How do I grab the selected radiobox value from a particular form?

I have some generated HTML along the lines of this.



<form id="form_56">
<input type="radio" name="option" value="0">
<input type="radio" name="option" value="1">
<input type="radio" name="option" value="2">
<input type="radio" name="option" value="3">
<input type="radio" name="option" value="4">
<input type="radio" name="option" value="5">
<input type="radio" name="option" value="6">
</form>





The form id can be anything, but I want to take a form ID and return the selected value from 0 to 6.

I tried following the questions here, but they didn't seem to translate easily to a specific form.

$('#form_56:radio[name=option]:checked').val();


I'm able to use the selector to grab the proper form, but everything I've attempted to get the selected value has returned undefined.

Thanks for your time.

Answer

First, you need to change the colon to a space or " > ".

Second you need to change radio to input.

$('#form_56 input[name=option]:checked').val();

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form_56">
  <input type="radio" name="option" value="0">
  <input type="radio" name="option" value="1">
  <input type="radio" name="option" value="2">
  <input type="radio" name="option" value="3">
  <input type="radio" name="option" value="4">
  <input type="radio" name="option" value="5">
  <input type="radio" name="option" value="6">
</form>

<a href="javascript:console.log($('#form_56 input[name=option]:checked').val());">
  <button>Test</button>
</a>

Comments