user974873
user974873

Reputation: 321

jQuery giving me the same value for any selected radio button?

I have the following radio buttons:

<fieldset data-role="controlgroup" data-type="horizontal">
<legend>Business Type</legend>
<input type="radio" name="businessType" value="business" id="business" checked="checked"/>
<label for="business">Business</label>
<input type="radio" name="businessType" value="personal" id="personal"/>
<label for="personal">Personal</label>
</fieldset>

I try to use this jQuery to get the current value of the selected radio button but I keep getting 'Business' as the value even if I select personal:

var idd = ($("input:radio[name=businessType]").val());

Thanks

Upvotes: 3

Views: 3509

Answers (2)

Zirak
Zirak

Reputation: 39808

Of course it'll return "Business" all the time. $("input:radio[name=businessType]") gives you all the radio-buttons with a specific name, not just the one selected, and .val returns the value of the first one - in this case, "Business".

You need to narrow down your selected elements, to only one - the elements selected. There's an easy way to do that:

$("input:radio[name=businessType]").filter(":checked").val();


As a side-note, your selector is pretty bad. You're selecting every single input box, then filtering them out. I'd suggest something like this:

$(containingForm).find("input:radio[name=businessType]")

That way, you're selecting one element (the containing form/other container), and finding the correct radio inputs within it only.

Upvotes: 2

Sajid
Sajid

Reputation: 4421

According to docs, you need to do:

var idd = ($("input:radio[name=businessType]:checked").val());

Upvotes: 12

Related Questions