Find HTML Label Associated With a Given Input

Find html label associated with a given input

First, scan the page for labels, and assign a reference to the label from the actual form element:

var labels = document.getElementsByTagName('LABEL');
for (var i = 0; i < labels.length; i++) {
if (labels[i].htmlFor != '') {
var elem = document.getElementById(labels[i].htmlFor);
if (elem)
elem.label = labels[i];
}
}

Then, you can simply go:

document.getElementById('MyFormElem').label.innerHTML = 'Look ma this works!';

No need for a lookup array :)

jQuery - select the associated label element of a input field

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!

How to find the closest label to an input?

You can use aria-labelledby attribute for this instead. The aria-labelledby attribute establishes relationships between objects and their label(s), and its value should be one or more element IDs.

Here, we can assume test2 is actually what you have in the code like this.element.id. Using that we can get the aria-labelledby attribute value using getAttribute() method. Then we can simply pass that to document.querySelector to get the closest label w.r.t the input id.

let input = document.querySelector(`#test2`)
let labelId = input.getAttribute('aria-labelledby')

let el1 = document.querySelector(`label[id="${labelId}"]`)
el1.style.color = "green"
<div>
<label id="interval">Interval</label><br>
<input min="0.1" id="test" placeholder="Min" step="0.1" type="number" aria-labelledby="interval">
<input min="0.1" id="test2" placeholder="Max" step="0.1" type="number" aria-labelledby="interval">
</div>

Why am I getting Form elements do not have associated labels even though there's a label associated with the input?

The <label> is present and is correctly linked to the <input>, but it is completely empty.
As a consequence, it is like if it was not present.

Your label must have some text content, so that screen readers can say something when landing on the input.
If you don't want that text to be displayed on screen, you can send it off screen, by using the visually hidden text technique.
Alternatively, you can add a an attribute aria-label on the input, which must also be non-empty for the same reason.

Get label for input field

Try to alert the contents of $label, you can use .text() for this

$('input').each(function(){
var $element = $(this)

if ($element.val() == '') {
var $label = $("label[for='"+this.id+"']")
alert($label.text())
}

});

Demo: Fiddle

Update

var $labels = $("label[for]");
var empties = $('input').filter(function(){
return $.trim($(this).val()) == ''
}).map(function(){
return $labels.filter('[for="'+this.id+'"]').text()
}).get().join(', ')

alert(empties)

Demo: Fiddle

Javascript: get radiobutton label with a specific for in label

You can do it with nextSibling:

var rdo = document.getElementById("option2");
var lbl;

rdo.style.display = "none";
for (lbl = rdo.nextSibling; lbl && lbl.nodeName.toUpperCase() !== "LABEL"; lbl = lbl.nextSibling) {
}
if (lbl) {
lbl.style.display = "none";
}

But I have a better option for you: It seems to be a well-kept secret that label elements can contain the input they relate to, and when they do no for is required at all. So if you change your HTML to:

<div id="myformelement">
<label><input type="radio" id="option1"> Option 1</label>
<label><input type="radio" id="option2"> Option 2</label>
<label><input type="radio" id="option3"> Option 3</label>
<label><input type="radio" id="option4"> Option 4</label>
</div>

...it gets a lot easier:

document.getElementById("option2").parentNode.style.display = "none";

You just find the input, traverse up to its parent which is the label, and hide that (which will hide the input as well).



Related Topics



Leave a reply



Submit