John Moore
John Moore

Reputation: 7129

Prevent enter firing button click in Vue.js

I am trying to sort out a user interface problem where an enter key pressed in an input field is effectively firing a click event on a button (presumably because it now has the focus). The button in question has a prevent modifier on its click action (i.e., <button @click.prevent="blah">), but that doesn't help. What I want to do is ensure that the button action is only executed by an actual click on the button, not by enter in a preceding input field.

LATER: I have this working now using <a @click.prevent="blah"> instead, with the link styled as a button via Bootstrap. This doesn't have the problem - an Enter key doesn't fire the handler. It seems insane to me that there is no way of distinguishing between a mouse click on a button and the Enter key firing it. Both are seen as a MouseEvent, and I can find no way of differentiating between the two.

Upvotes: 3

Views: 4480

Answers (3)

C. Foust
C. Foust

Reputation: 31

What worked best for me was an empty @click.prevent="" in combination with @mousedown.prevent="myfunction".

This:

  • prevents the 'Enter' key from triggering a click
  • keeps the tag from receiving focus on click (except on keyboard navigation)
  • prevents page reload on any href="#"

My fiddle: https://jsfiddle.net/j8fchbvk/37/

Upvotes: 2

Katinka Hesselink
Katinka Hesselink

Reputation: 4173

In a similar situation I fixed it by getting rid of the <form> tag . Since Vuex was handling form-submission, I did not need the form tag anyhow.

Upvotes: 0

John Moore
John Moore

Reputation: 7129

Actually, the answer was extraordinarily simple, but not immediately obvious. I was using plain <button>. I had forgotten to add what the type tag, which I normally would, thus: <button type="button"> Once this was in place, the Enter key no longer fired it.

Upvotes: 17

Related Questions