How to Determine Which Radio Button is Selected?
A very common task in jQuery is to determine which radio button is selected.
Consider this form…
with this HTML …
Notice that the HTML has coffee selected as the default choice with the checked attribute. Keep in mind that the attribute is “checked” and not “selected”.
Determine Which Radio Button was Selected
We add the following jQuery code at the bottom of the page just before the closing </body> tag.
Now when the button is clicked, it tells us which beverage was selected…
We are querying for input elements named “beverages” that are checked. This should return the selected radio button. Calling val() on the selected radio button will return the value of the radio button that was selected — the value being the attribute value in the HTML of that input tag.
Determine if a particular radio button was selected
Now if we wanted to determine if the “tea” radio button in particular was selected or not, we do …
We use jQuery selection to select the “tea” input tag specifically: $(‘input[value=tea]’)
Then we call the prop() method to see if its property is “checked”. Please remember to call it with prop(“checked”) and not prop(“selected”).
Another way of determining if “tea” was selected is to use the “is()” method …
But you have to remember to pass it “:checked” — note the colon in front. When you use the is() method, you have to use the “:checked”.
$(‘input[value=tea]’).is(“:checked”)
will return true if and only if the input tag with value=tea is checked.
Yet another way to determine if “tea” is selected is to query for the input element whose value is tea and is checked…
If that element is found and returns a valid value from the val() method, then Tea radio button must have been selected. If that element is not found, the val() method will return undefined making the if condition false and alerting us that tea was not selected.
Do Not Use the Attr() to Determine if Radio button is selected
With all these ways to check if a radio button is selected, what you do not want to do is this …
Do not use the attr() method for checking if the radio button is selected. This will not work. If you run it, it will always say that “Tea was not selected”. That is because (if you look back at the HTML), the tea radio never has the “checked” attribute. Hence …
$(‘input[value=tea]’).attr(“checked”)
will always return false.
The attr() checks for the attribute in the HTML. It does not check for the “checked” state. For the “checked” state, you have to use prop(“checked”) as shown previously.
Because “checked” is seen in the above HTML for the coffee input tag,
$(‘input[value=coffee]’).attr(“checked”)
will always return true.