nich nich - 1 year ago 58
Javascript Question

In jQuery, how do I get the value of a radio button when they all have the same name?

Here is my code:

<td>Sales Promotion</td>
<td><input type="radio" name="q12_3" value="1">1</td>
<td><input type="radio" name="q12_3" value="2">2</td>
<td><input type="radio" name="q12_3" value="3">3</td>
<td><input type="radio" name="q12_3" value="4">4</td>
<td><input type="radio" name="q12_3" value="5">5</td>
<button id="submit">submit</button>

Here is JS:


Here is JSFIDDLE! Every time I click button it returns 1. Why? Can anyone help me?

Answer Source

Fiddle demonstrating this behaviour.

In your code, jQuery just looks for the first instance of an input with name q12_3, which in this case has a value of 1. You want an input with name q12_3 that is :checked.

$("#submit").click(function() {     

Note that the above code is not the same as using .is(":checked"). jQuery's is() function returns a boolean (true or false) and not an element.