I assume that the reason for placing the input
inside the label
is that you can switch the βselectedβ class depending on the status of the flag and work with it when you click on either the label or the flag.
Here is one way to achieve this while saving the label
and input
separately: http://jsfiddle.net/pkuCe/
$('#cb').change(function(){ $("label[for=cb]").toggleClass("selected", this.checked); });
This sets the class to label
depending on the status of the flag and should work when the flag or label is clicked.
Why is your current approach not working?
From the specs , there is nothing wrong with nesting the input
in the label
tag:
for = idref [CS]
This attribute explicitly associates a label defined with another control. If present, the value of this attribute must match the value of the id attribute of some other control in the same document. If absent, the defined label is associated with the content of the element.
However, it seems that the problem you are talking about is because the click
event is fired twice (thus invalidating the switch) when you have a nested input
element. I have not tested it in all browsers, but it seems to be happening in FF8.
Try clicking on the label in this example: http://jsfiddle.net/cRnJS/
Apparently, clicking on the label
elements triggers a click
event in the input
associated with it (therefore check / uncheck works), and this event bubbles up, therefore, it fires it a second time in the parent label
,
conclusions
- HTML specs are wise, you can have
input
nested in a label
, but it would be wise to leave them separate - Use the
change
event instead of click
. (note: you can have multiple labels for each input
)
source share