0

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.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Buggabill
  • 13,726
  • 4
  • 42
  • 47

4 Answers4

5

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

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

Chris
  • 4,393
  • 1
  • 27
  • 33
3

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") + "]");
Daff
  • 43,734
  • 9
  • 106
  • 120
  • Interesting... How would I use `label` in my script? I may be missing what you are going for here. After assigning `label`, would I do something like `label.addClass("chksel");`? – Buggabill Nov 27 '10 at 00:31
  • I did a little research and figured out what you were going for here. I absolutely loved it! It cut a bunch of code out of my particular situation. I used this as a guide - http://stackoverflow.com/questions/285522/find-html-label-associated-with-a-given-input/285565#285565. Thanks a bunch! It was way cooler! – Buggabill Nov 27 '10 at 01:17
  • 1
    Glad you figured it out. The neat thing about that solution is, that you don't need a bunch of unnecessary ids. You can use label as a jQuery object and also wrap it into $(label) (using a jQuery object on a jQuery object will return that object). – Daff Nov 27 '10 at 01:27
1

Try adding "#":

var lblid = "#" + $(this).attr("id") + "_lbl";
dubrox
  • 664
  • 6
  • 11
1

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

Gabriele Petrioli
  • 191,379
  • 34
  • 261
  • 317