Home>

The crux of the problem: when an input and a button are wrapped in a form, pressing Enter on the input fires the click event on the button. Why is this happening and how to make it so that clicking on the button does not work?

const btn= document.querySelector('button')
btn.addEventListener('click', (e)=> {
  console.log(e.type, e.target.nodeName)
})
const form= document.querySelector('form')
form.addEventListener('submit', (e)=> {
  e.preventDefault()
})
<form action="">  <input type="text">  <button>Button</button></form>

It's not in the button, but in the form, all her life she has such default behavior, it seems

Алексей Шиманский2022-01-14 09:06:28

And if you click on the button -what is expected? That the form will be submitted without the participation of js or will the form submission be processed through js?

Алексей Шиманский2022-01-14 09:08:56

@Aleksey Shimansky, that one is not. Clicking the button has a different behavior. In a real project, the button does not belong to the input, logically at all. This is the very pulp I described here. "Bug" -in its purest form. The situation is much more complicated. Application on Vue, c with a bunch of components

Дмытрык2022-01-14 09:11:11

Add an input with type="button" instead of a button and an onclick handler that will submit the form. Or explicitly prohibit sending by key code enter ..

Rudi2022-01-14 09:13:13

@Rudi yes it helps. I don’t know yet how applicable it is for me -I have to think. But there is at least one option. Thank you

Дмытрык2022-01-14 09:18:10