Reputation: 948
I'm attaching an onchange
event on checkboxes like this:
$("input[type='checkbox'][name='auswahl[]']").on("change", function() {
alert($(this).attr("id") + ' ' + $("label[for='" + $(this).attr("id") + "']").text() + $(this).attr("checked"));
});
The checkboxes look like this:
<input type="checkbox" name="auswahl[]" id="aus_nunatsiaqnews_ca"><label for="aus_nunatsiaqnews_ca" title="Canada">Nunatsiaq News</label>
Unfortunately the event is firing twice. When I isolate the code given above and put it on a test page everything is fine and the event is firing only once. Need help.
Upvotes: 2
Views: 5052
Reputation: 782
This usually happens when a control with an "onClick" event is nested inside another control with an "onClick" event. Clicking one of the elements triggers the events for both elements since there is no way of knowing which of them you wanted to click. fortunately, this can be prevented in Javascript. in the HTML, pass the "$event" parameter to the function that handles the click event like so:
onClick="myFunc($event)"
and then, in "myFunc" use "stopPropagation" as such:
myFunc($event) {
// ... some code ... //
$event.stopPropagation();
}
Upvotes: 6