Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Onclick is called twice

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.

like image 575
k102 Avatar asked Dec 15 '22 13:12

k102


2 Answers

event.preventDefault(); instead of event.stopPropagation(); triggers onclick on the clicked element only. A demo at jsFiddle.

like image 124
Teemu Avatar answered Dec 27 '22 19:12

Teemu


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>
like image 26
Kevin G Flynn Avatar answered Dec 27 '22 19:12

Kevin G Flynn