Why using attr to detect selected radio button appears to give wrong answer in jQuery?
Have you ever used attr method in jQuery and it seems to give the wrong answer? The key word here is “seems”. It actually does give the correct answer. But our usage of it is wrong. Let me demonstrate.
Suppose, we want to detect if the user selected “tea” when the button is clicked …
As you can see, it gave the wrong result because we had been using some incorrect code like this …
The idea had been to select the input tag with the value “tea” (ie the tea radio button) and see if it is checked using the attr method…
$('input[value=tea]').attr("checked")
The reason why this is not correct is that this will return true if and only if the “checked” attribute is in the HTML code. And if you look at the HTML for that radio button …
<input type="radio" name="beverages" value="tea" />Tea<br />
there is no checked attribute. Therefore this expression will always return false even if the user had selected the tea radio button. That is what the attr method does. It looks to see if that attribute is found in the HTML element. It does not detect the state of the radio button.
What we should have done is to use prop …
What we should have done is to use the prop method as in …
This will work as expected because the prop method returns the state of the radio button (as to whether it is checked or not). Make sure you use …
prop("checked")
and not …
prop("selected")
as the latter will not work.
This is what the attr method does
Note that the coffee radio button does have the checked attribute in the HTML …
<input type="radio" name="beverages" value="coffee" checked />Coffee<br />
which means that this radio button is selected by default when the page first comes up.
That means that if we use the attr method to detect if coffee is the default choice as in …
then …
$('input[value=coffee]').attr("checked")
will always return true (regardless of what the user selected). attr returns true for this coffee radio button because “checked” is an attribute of the HTML element.
Learn more about how to detect which radio button is selected in this tutorial.