StaceyH
StaceyH

Reputation: 739

JQuery: get radio button value

I have the following HTML:

HTML:

<input type="radio" name="abc" value="0" selected="selected" style="display:none" />
<input type="radio" name="abc" value="1" />1+
<input type="radio" name="abc" value="2" />2+
<input type="radio" name="abc" value="3" />3+

JQuery to get the selected radio button

$('input:radio[name=abc]:checked').val();

Why doesn't the code above work on page load, BEFORE a user selected a radio button? It's strange because the code above does work AFTER a user selected a radio button.

It seems to me that I have set the default radio button value to be 0, but if you

Meaning, if the radio button value is selected, return the selected value - otherwise, return 0 (when no value has been selected)

Upvotes: 21

Views: 45030

Answers (3)

Ashish Babu
Ashish Babu

Reputation: 1175

First correct the attribute to checked and remove selected attribute which is wrong and then use the following code. t will get the selected value of the radiobutton at button click. ex for list

   $("#btn").click(function() {
        $('input[type="radio"]:checked').val();
        });

Upvotes: 20

Šime Vidas
Šime Vidas

Reputation: 186103

You are using the wrong attribute. For radio buttons you have to use the checked attribute and not the selected attribute.

<input type="radio" checked="checked">  

or just:

<input type="radio" checked>

Upvotes: 23

Galen
Galen

Reputation: 30180

Radio has the attribute checked, not selected

<input type="radio" name="abc" value="0" checked="checked" style="display:none" />
<input type="radio" name="abc" value="1" />1+
<input type="radio" name="abc" value="2" />2+
<input type="radio" name="abc" value="3" />3+

Upvotes: 8

Related Questions