Javascript fires two events - onkeypress and onclick

podeig picture podeig · Mar 2, 2010 · Viewed 18.2k times · Source

Problem is when I press a key over a radio button, element MyFunc fires twice - once for "onkeypress" event, another time for "click" event.

Question "Why?" I need to handle this by two different ways, but now I can not recognize what initial event was. When I click a mouse it fires just for "click" event.

<ul>
    <li>
        <input type="radio" onkeypress="MyFunc(event, this)" onclick="MyFunc(event, this)" name="myList" id="MyId_1" />Topic 1
        <input type="radio" onkeypress="MyFunc(event, this)" onclick="MyFunc(event, this)" name="myList" id="MyId_2" />Topic 2
    </li>
</ul>

function MyFunc(e, obj) {
    alert(e.type); // alerts "keypress" and then "click"
    // Do my stuff
}

Thank you for help!

Answer

pooja sharma picture pooja sharma · Feb 13, 2016

If 2 events are being fired during pressing a key then check event.detail property in onClick function. if event.detail = 0 then it means that mouse was not clicked on that element and we can ignore it. event.detail