Search code examples
htmlprototypejsradio-buttonlabel

How to find the connection between a radio button and a label?


I have this label:

<label id="options_31409_3label" for="options_31409_3"><span>some text</span></label>

As you see, there is some text in the label inside a span. Now I also have a radio button, which is left of the label:

<input id="options_31409_3" class="radio" type="radio" value="72058" name="options[31409]" onclick="xyz()">...</input>

This is one radio and one label, but I have several radio buttons and labels on the same site. Now from those N labels and radio buttons I have to identify one pair and do some Prototype stuff with it. The pair has a different id each time the site is loaded, the only thing that stays is the text inside the span. Is there a way to get the label and the radiobutton if there is "some text" inside the span? I can use Prototype if that helps.

Thanks!


Solution

  • Because you know that label's id consists of input's id + 'label', you can use e.g. the following code to find a pair:

    $$('input[type=radio]').each(function() 
        var input = this;
        var label = $(this.id + 'label');
        // do something for input and label
    });