I have a span element that replaces a checkbox so I can style it. I also have a label tag; when clicked it should fire the span’s click event as if the user has just clicked the span element. In other words – I’m mimicking the label/checkbox relationship with label/span.
This functionality works as intended in Firefox and Chrome but not IE. In IE 7 and 8, clicking the label does nothing and seems to generate some odd attribute in the source:
<span class="checkbox" id="Vechicle-1" jQuery15105041923284548672="2"/>
<label class="large text-left" for="Vechicle-1" jQuery15105041923284548672="24">
In IE 9 I do not see the jQuery string appended and 2x clicking the label will fire off the span’s click event.
$('.checkbox').click(function () {
$(this).toggleClass('checked');
if ($(this).hasClass('checked')) {
$('#checkbox-' + $(this).attr('id')).attr('checked', 'checked');
} else {
$('#checkbox-' + $(this).attr('id')).removeAttr('checked');
}
});
$('label').click(function () {
$('#' + $(this).attr('for')).click();
});
Any idea what’s causing this behavior?
Maybe the click event is bubbling upwards and trigger some other code you might have, try to prevent it by changing the code to:
And the same for the other click handler.
Edit: found the root of this behaviour. As it turns out, IE browser “let” label affect non form elements as well, including
<span>meaning that clicking label element will trigger theclickevent of the element having ID defined as the labelforattribute – no matter what is the element type.Chrome (and probably Firefox) would let it trigger only form elements like checkbox, as expected.
Proof of this can be found here just browse with IE browser (even 9) and see the span is “clicked” when label is clicked even though the jQuery line is commented.
(Code in fiddle is the same as in the original question)
All this boils down to the interesting conclusion: clicking the label caused the span to be clicked twice – one time by the browser and another by jQuery code, causing it to toggle its state twice.