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.
$('input'). change(function() { if (this. checked) { var response = $('label[for="' + this.id + '"]'). html(); } });
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.
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.
$('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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With