Buggabill
Buggabill

Reputation: 13901

Adding a class to a label with JQuery

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

Answers (4)

Gabriele Petrioli
Gabriele Petrioli

Reputation: 196002

change the selector to $('#'+lblid)

Upvotes: 1

dubrox
dubrox

Reputation: 649

Try adding "#":

var lblid = "#" + $(this).attr("id") + "_lbl";

Upvotes: 1

Daff
Daff

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

Chris
Chris

Reputation: 4471

I think you are missing a # in your ID string.

var lblid = "#" + $(this).attr("id") + "_lbl";

Upvotes: 5

Related Questions