开发者

odd behavior when checking if radio button selected in jQuery

开发者 https://www.devze.com 2022-12-28 14:53 出处:网络
I had the following check in my jQuery which I thought was working fine to see if a radio button was checked.

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, i开发者_StackOverflowt 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!


Try this:

var id = $("input[name='companyType']:checked").attr('id');
alert(id);
if (id == "primary") {
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号