Reputation: 13901
I am trying to add a class to a label of a checkbox on the click event of the checkbox with jQuery. I am calling the following function after retrieving the HTML for the checkboxes in an ajax call.
function modDispTable() {
$("#disptbl :input").each(function () {
$(this).click(function () {
var lblid = $(this).attr("id") + "_lbl";
if ($(this).is(":checked")) {
$(lblid).addClass('chksel');
}
else {
$(lblid).removeClass('chksel');
}
});
});
}
There are more checkboxes, but the resulting HTML for all of the checkboxes looks similar to this:
<label id="chk_sobomnifeat_lbl" name="chk_sobomnifeat_lbl" for="chk_sobomnifeat" class="radiolbl chkmod chkmod1">
<input id="chk_sobomnifeat" name="chk_sobomnifeat" value="chk" type="checkbox">
Sobella Omni Feature Display
</label>
Right now, all that I am trying to do is apply a different background color. The CSS is in a file that is included with the page.
.chksel {
background-color: #D3CEBE;
}
I am not getting any errors. Debugging in Firebug has me even more baffled as the click events are triggered, lblid
contains the correct id value (the label's), and the addClass
line is supposedly executed.
Does anyone have any ideas why the class will not apply? I am using JQuery 1.4.4.
Upvotes: 0
Views: 6424
Reputation: 44215
You probably need the id selector like:
var lblid = "#" + $(this).attr("id") + "_lbl";
But even cooler woud be (since you are using the proper markup already):
var label = $("[for=" + $(this).attr("id") + "]");
Upvotes: 3
Reputation: 4471
I think you are missing a #
in your ID string.
var lblid = "#" + $(this).attr("id") + "_lbl";
Upvotes: 5