Wednesday, April 13, 2011

hide() radio button *and* its text label in jquery

Hi

I am going back over a recent project sorting out accessibility issues and was making sure all form elements had labels. Putting the label text into a tag caused a problem with some kludgy code I had written before.

Basically, if you have a radio button and its label:

<label for="zone_r1"><input type="radio" name="zone" id="zone_r1" value="NY" />New York</label>

And you use jquery to hide it like so:

$('#zone_r1').hide();

The actual button is hidden but not the label text. Originally I made a span for the label text and hid that like so:

<input id="NY" type="radio" name="zone" value="NY" /><span id="nyTXT">New York</span>

and

$('#NY').hide();
$('#nyTXT').hide();

Any ideas? I prefer not to use the kludge and it may not validate with the span in the label, but maybe I am being overly zealous.

From stackoverflow
  • $('#zone_r1').parent().hide();
    

    works for me

  • what about $('label:has(#zone_r1)').hide();

  • For the first radio button, you can hide the actual button and then its parent:

    $('#zone_r1').hide().parent().hide();
    

    For the second case you can hide the button and the "next" sibling:

    $('#NY').hide().next().hide();
    
  • I think this should work for you

    $("label[for=zone_r1],#zone_r1").hide();
    

    This selects the label with the "for" attribute set to the radio button your looking for, as well as the radio button itself, and hides them both

  • You can do this:

    1.) Define the radio button input without a surrounding label.

    2.) Wrap the "option text" (text to the right of the radio button) in a <span>.

    3.) Use this jQuery statement: $("input:radio:not(:checked), input:radio:not(:checked) + span").hide();

    This will select the radio button and the text to the right of the radio button and hide it.

0 comments:

Post a Comment