Search code examples
javascriptjqueryforms

jQuery - select the associated label element of a input field


I have a set of input fields, some of them have labels associated, some not:

<label for="bla">bla</label> <input type="text" id="bla" />

<label for="foo">bla <input type="checkbox" id="foo" /> </label>

<input ... />

so, how can I select the associated label for each input, if it exists?


Solution

  • You shouldn't rely on the order of elements by using prev or next. Just use the for attribute of the label, as it should correspond to the ID of the element you're currently manipulating:

    var label = $("label[for='" + $(this).attr('id') + "']");
    

    However, there are some cases where the label will not have for set, in which case the label will be the parent of its associated control. To find it in both cases, you can use a variation of the following:

    var label = $('label[for="' + $(this).attr('id') + '"]');
    
    if(label.length <= 0) {
        var parentElem = $(this).parent(),
            parentTagName = parentElem.get(0).tagName.toLowerCase();
        
        if(parentTagName == "label") {
            label = parentElem;
        }
    }