Prevent onclick event on a button from firing when hitting Enter in a different box
Its default HTML behaviour. All the buttons
inside a form
are of type="submit"
. On pressing enter
, the most recent button of the form
is clicked and their handlers are called, by default. To fix this, the buttons are created with type="button"
.
console.log(document.querySelector("#a").type)
console.log(document.querySelector("#b").type)
console.log(document.querySelector("#c").type)
<form>
<input type="text">
<button id="a" onclick="console.log('a')">Submit type</button>
<button id="b" onclick="console.log('b')" type="button">Button type</button>
<input id="c" type="submit" value="Input Submit type">
</form>
You can refer this to understand the behaviour of <button>
and <input type="button">
.
If you just check in console like, document.querySelector("#box").children[1].type
it will show as submit
.
Button, by default, acts as submit
type unless it is specified explicitly (either submit
(default)/reset
/button
). Just run document.querySelector("#box").children[1].type=button
. You find it working as expected.
The behaviour is same in cross-browser and tested in Firefox Nightly
(developer version), Chrome
and Safari
and works a little bit different in IE
.
Also you can see the click is by default by seeing console.log(event.detail)
is 0
as it is triggered internally. When triggered with a left click, it would be 1
. MDN Docs on click event