Reputation: 840
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.
Upvotes: 17
Views: 51063
Reputation: 77956
$('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/
Upvotes: 42
Reputation: 3065
here is the basic example as per your requirement. You need the html content from the label next to your checkbox, if it is checked.
use this
HTML
<div>
<form >
<input type="checkbox" id="yes" /><label for="yes">text yes </label>
<input type="checkbox" id="no" /><label for="no">text no</label>
</form>
</div>
JQUERY
$('input').change(function() {
if (this.checked) {
var response = $(this).next("label").html();
alert(response);
}
})
Upvotes: 0
Reputation: 15931
your syntax was a little wacked, try setting up the HTML like so
<input id="yes1" type="checkbox" />
<label for="yes1" id="yes1-label">This is the label</label>
and then use jquery like so
$("#yes1").click(function() {
if ($("#yes1").is(":checked")) {
/* it's not really clear what you are trying to do here */
var response = $("#label").attr("id");
$("#yes1-label").text(response);
}
});
Upvotes: -2