Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery given input ID, get label text

In my HTML forms (as in most HTML forms), the labels share the same IDs as the fields. I'm trying to return to HTML of the label tag once the checkbox with a matching ID is clicked.

<input id="yes1" type="checkbox">
<label for="yes1">This is the text it should return.</label>

And my jQuery:

$('input').change(function() {
    if (this.checked) {
        var response = $('label#' + $(this).attr('id')).html();
    }
}

But alas, response comes out as NULL.

like image 311
delwin Avatar asked Dec 12 '11 06:12

delwin


People also ask

How to get input label text in JQuery?

$('input'). change(function() { if (this. checked) { var response = $('label[for="' + this.id + '"]'). html(); } });

How do I get element labels?

Use the textContent property to get the text of a label element, e.g. const text = label. textContent . The textContent property will return the text content of the label and its descendants. If the element is empty, an empty string is returned.

What is htmlFor in label?

htmlFor property reflects the value of the for content property. That means that this script-accessible property is used to set and read the value of the content property for , which is the ID of the label's associated control element.


1 Answers

$('input').change(function() {
    if (this.checked) {
        var response = $('label[for="' + this.id + '"]').html();
    }
});

No need to get the id from the attribute.

Demo: http://jsfiddle.net/wycvy/

like image 62
AlienWebguy Avatar answered Sep 28 '22 00:09

AlienWebguy