2

I've got a form and I'm trying to catch the submit event, in case the user hits the enter key inside a text input.

This works fine UNTIL I also try to catch a button click and prevent the default action.

I want to be able to handle the button click and enter key inside the input differently - but the button is overriding the form's submit.prevent method.

See the example below, the first text field and button trigger "one event" but the second form has an event on the button, but that's overriding the form submit.

I want the enter key in the input to set the title to "two events" but the button to set the title to "double"

Is it something to do with the event bubbling up?

var myApp = new Vue({
	'el' : '#myApp',
  'data': {
  	'title' : 'potato'
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.4/vue.js"></script>
<div id="myApp">
  
  <h1>
    {{title}}
  </h1>

  <form method="POST" @submit.prevent="title = 'one event'">
    <input type="text" />
    <button>One event</button>
  </form>
  
  <form method="POST" @submit.prevent="title = 'two events'">
    <input type="text" />
    <button @click.prevent="title = 'double'">Two events</button>
  </form>  
</div>

1 Answer 1

3

Since you are preventing the forms from submitting anyway, why not change the type of the button (which defaults to submit).

<button type="button" @click="title = 'double'">Two events</button>

var myApp = new Vue({
	'el' : '#myApp',
  'data': {
  	'title' : 'potato'
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.4/vue.js"></script>
<div id="myApp">
  
  <h1>
    {{title}}
  </h1>

  <form method="POST" @submit.prevent="title = 'one event'">
    <input type="text" />
    <button>One event</button>
  </form>
  
  <form method="POST" @submit.prevent="title = 'two events'">
    <input type="text" />
    <button type="button" @click.prevent="title = 'double'">Two events</button>
  </form>  
</div>

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

1 Comment

totally forgot about type on a button - will go refresh my memory on that, have a bad feeling I've had exactly the same problem before. thanks @bert

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.