views:

150

answers:

1

Hi, I have the following code in jQuery for a set of radio buttons which all have the same behaviour on click (they show some hidden fields). I was previously duplicating the same code for each individual selector, so i just used multiple selectors as in the code below. However, this doesn't really work, as when a couple of the radio buttons are on the same page, the correct show/hide behaviour seems to be messed up. Is this because i'm using $(this) with live()? Or is there something else i'm doing wrong? Thanks for any help, just trying to keep this code as clean as possible, want to avoid having to duplicate it over and over again for each selector!

//event handler for radio fields with subsections
        $("input[name='registered'], input[name='voted'], input[name='report'], input[name='newsletter']").live("click", function(){
            //check if value is true
            if ($(this + ":checked").val() == '1') 
                $(this).parent().find('span.hidden').fadeIn("slow");
            else 
                $(this).parent().find('span.hidden').hide();
        });
+1  A: 

Your selector in your if statement isn't correct. Try:

if ($(this).filter(':checked').val() == '1')

or even

if ($(this).val() == '1')

The way you had it, it would stringify the this element and prepend it to "checked". Obviously not what you want. What you want is to see if the clicked element -- only one will fire the event so this will correspond to the clicked element, thus removing the need for the filter, I believe -- has the correct value.

tvanfosson
don't forget the $(this).is(':checked') option too - that one always seems the easiest to read.
Scott Ivey
Thanks guys - works perfectly.
steve-o