Further to my previous question, I have a jQuery event that I want to fire when the checkbox and the label itself is clicked.
jsFiddle example here.
My problem is that when I click the label, it doesn't fire the function. The checkbox works fine, as you can see.
Is there anything more I can add? Or is this it?
Thanks :)
EDIT: code from jsFiddle link
HTML
<div id="scrollwrap">
<div>
<input value="1" type="checkbox" name="salgsvilkar" id="checkbox2" style="float:left;"/>
<label for="checkbox2" class="akslabel">Salgs og leveringsvilkår er lest开发者_Go百科 og akseptert</label>
</div>
</div>
jQuery
$(function() {
//checkbox
$("#checkbox2, .akslabel").click(function() {
$("#scrollwrap").toggleClass('highlight');
});
});
You can change it a bit like this to be safe:
$(function() {
$("#checkbox2").change(function(){
$("#scrollwrap").toggleClass('highlight', this.checked);
});
});
You can test it out here. The advantage here is you can add a .change()
on the end to make the state match if it's initially checked, like this:
$(function() {
$("#checkbox2").change(function(){
$("#scrollwrap").toggleClass('highlight', this.checked);
}).change();
});
You can test that version here. You can also make this much more generic, like this.
this should do it:
$(function() {
//checkbox
$("#checkbox2").change(function(){
$("#scrollwrap").toggleClass('highlight');
});
});
The reason it didn't work when you had click()
is because clicking on the label triggers the event twice since it is attached to both elements - which means it will toggle the class name twice!
精彩评论