jQuery - select the associated label element of a input field

JavascriptJqueryForms

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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;
	}
}

I hope this helps!

Solution 2 - Javascript

There are two ways to specify label for element:

  1. Setting label's "for" attribute to element's id
  2. Placing element inside label

So, the proper way to find element's label is

   var $element = $( ... )

   var $label = $("label[for='"+$element.attr('id')+"']")
   if ($label.length == 0) {
     $label = $element.closest('label')
   }

   if ($label.length == 0) {
     // label wasn't found
   } else {
     // label was found
   }

Solution 3 - Javascript

As long and your input and label elements are associated by their id and for attributes, you should be able to do something like this:

$('.input').each(function() { 
   $this = $(this);
   $label = $('label[for="'+ $this.attr('id') +'"]');
   if ($label.length > 0 ) {
       //this input has a label associated with it, lets do something!
   }
});

If for is not set then the elements have no semantic relation to each other anyway, and there is no benefit to using the label tag in that instance, so hopefully you will always have that relationship defined.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAlexView Question on Stackoverflow
Solution 1 - JavascriptjgradimView Answer on Stackoverflow
Solution 2 - JavascriptMaxim KulkinView Answer on Stackoverflow
Solution 3 - JavascriptNathan AndersonView Answer on Stackoverflow