3

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.

2
  • In your event handler, have you tried e.preventDefault()? Commented Nov 19, 2017 at 18:50
  • 1
    Isn't that what @click.prevent does for me? Commented Nov 19, 2017 at 19:09

3 Answers 3

17

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Wow! I can't believe this was it. This had been killing me for so long! Thank you so much. I have never come across this before.
Same here, days looking for the answer!! thanks bro
2

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/

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.