tags:

views:

50

answers:

2
+2  Q: 

jQuery and labels.

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 og akseptert</label>
    </div>
</div>

jQuery

$(function() {
    //checkbox
    $("#checkbox2, .akslabel").click(function() {
        $("#scrollwrap").toggleClass('highlight');
    });
});
+2  A: 

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!

Mouhannad
Thanks for the explanation!
Anzeo
Be aware that on some browsers (read: IE) the onchange event of a checkbox is fired only after it loses focus, not at the time of the click itself.
Joeri Hendrickx
+4  A: 

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.

Nick Craver
Great, the second version is exactly what I was trying to accomplish! Thanks again, Nick. Is there anything that jQuery can't do?
Kyle Sevenoaks
@Kyle - unfortunately it doesn't cook the waffles, that part is manual
Nick Craver
It can't make you applepie...But it can make you a nice pie-chart with the right plugins :)
Justus Romijn
@Nick, well damn!@Justus, mmmm pie...
Kyle Sevenoaks