Reputation: 8089
Here's the code:
<label onclick="event.stopPropagation(); alert(event.target.innerHTML);">
<button>
button
</button>
<span>
span
</span>
</label>
(and the fiddle: http://jsfiddle.net/YsYKq/1/)
If one clicks on the button, only button
is alerted, but when on span - both span
and button
are alerted - so the onclick
function is called twice.
How can I prevent this? I need onclick
to be called only once.
Upvotes: 4
Views: 14900
Reputation: 177
I have solved this using different id field for label and checkbox - and then testing event.target.label for label script
function selectIconElement(elem, event){
if(event.target.id.indexOf('label')>0){
//do something if its label
}else{
//do something if not label
}
}
Upvotes: 0
Reputation: 12965
...click event gets fired twice when user click on any of the item in iscroll...
https://groups.google.com/forum/#!topic/iscroll/XL2Ny9gpKc0
Upvotes: 0
Reputation: 448
Suggestion by @BenM Goes Perfect But if you still want to use enclosing button and span then here's a way...
<label for="notExistingId" onclick="event.stopPropagation(); alert(event.target.innerHTML);">
<button>
button
</button>
<span>
span
</span>
Just provide a value of 'for' in label with an ID which do not exist.
Hope it helps..
Upvotes: 0
Reputation: 23416
event.preventDefault();
instead of event.stopPropagation();
triggers onclick
on the clicked element only. A demo at jsFiddle.
Upvotes: 8
Reputation: 231
Please try below code i am editing your code and change "stopPropagation" to "preventDefault".
<label onclick="event.preventDefault(); alert(event.target.innerHTML);">
<button>
button
</button>
<span>
span
</span>
</label>
Upvotes: 5