odd behavior when checking if radio button selected in jQuery
Posted
by RememberME
on Stack Overflow
See other posts from Stack Overflow
or by RememberME
Published on 2010-04-24T22:31:12Z
Indexed on
2010/04/24
22:33 UTC
Read the original article
Hit count: 173
I had the following check in my jQuery which I thought was working fine to see if a radio button was checked.
if ($("input[@name='companyType']:checked").attr('id') == "primary") {
...
}
Here's the radiobuttons:
<p>
<label>Company Type:</label>
<label for="primary"><input onclick="javascript: $('#sec').hide('slow');$('#primary_company').find('option:first').attr('selected','selected');" type="radio" name="companyType" id="primary" checked />Primary</label>
<label for="secondary"><input onclick="javascript: $('#sec').show('slow');" type="radio" name="companyType" id="secondary" />Subsidiary</label>
</p>
Then, it suddenly stopped working (or so I thought). I did some debugging and finally realized that it was returning an id of "approved_status". Elsewhere on my form I have a checkbox called "approved_status". I realized that when I originally tested this, I must have testing it on records where approved_status is false. And, now most of my approved_statuses are true/checked.
I changed the code to this:
var id = $("input:radio[@name='companyType']:checked").attr('id');
alert(id);
if (id == "primary") {
And it's now properly returning "primary" or "secondary" as the id.
So, it is working, but it seems that it's not checking the name at all and now just checking radio buttons. I just want to know for future use, what's wrong with the original code b/c I can see possibly having 2 different radio sets on a page and then my new fix probably wouldn't work. Thanks!
© Stack Overflow or respective owner