Avoid form Ubmit by pressing the Enter key

Asked

Viewed 2,359 times

1

I have a input in the Vuejs that is inside a form and when I press enter I don’t want the form is submitted.

Together with Vuejs I am using Quasar and I was able to assign the function call only in the key enter:

<form @keydown.enter="evitarSubmit">

Function:

evitarSubmit () {
  console.log('Tentou evitar')
}

I’m having a hard time finding and drafting a code that nullifies the effect of enter about the form, but I accept suggestions...

  • if you’re getting right into the evitarSubmit(), just put a event.preventDefault(), that it cancels the Ubmit form.

  • https://stackoverflow.com/questions/895171/prevent-users-from-submitting-a-form-by-hitting-enter

2 answers

3


You have many ways. One of them is to use @keydown.enter.prevent in <form>. This prevents Submit but also prevents enter to be used where it was pressed, and perhaps this effect is unwanted.

Another way is to use @keydown.enter.stop locally in the input in question, or by creating a div around these inputs and put there to prevent the event from propagating up to the form.

new Vue({
  el: "#app",
  data() {
    return {
      input1: '',
      input2: '',
      textarea: ''
    }
  }
});
<script src="https://unpkg.com/vue/dist/vue.min.js"></script>
<div id="app">
  <form action="/foo">
    <div @keydown.enter.stop>
      <input type="text" v-model="input1" />
      <input type="text" v-model="input2" />
      <textarea v-model="textarea"></textarea>
    </div>
  </form>
  <p>{{input1}}</p>
  <p>{{input2}}</p>
  <p>{{textarea}}</p>
</div>

Obs:

There is one detail to consider. Browsers behave differently when they only have 1 input. Then the top method doesn’t work and you have to use something like this:

new Vue({
  el: "#app",
  data() {
    return {
      input: '',
      textarea: ''
    }
  }
});
<script src="https://unpkg.com/vue/dist/vue.min.js"></script>
<div id="app">
  <form action="/foo">
      <input type="text" v-model="input" @keydown.enter.stop.prevent/>
      <textarea v-model="textarea"></textarea>
  </form>
  <p>{{input}}</p>
  <p>{{textarea}}</p>
</div>

1

Capture enter in your form and prevent the submit shoot like this:

event.returnValue=false;
event.cancel = true;

Follows example working:

function EnterKeyFilter()
{  
  if (window.event.keyCode == 13)
  {   
      event.returnValue=false;
      event.cancel = true;
  }
}
<form onkeydown="EnterKeyFilter();">
  <input type="text" name="teste" placeholder="pressione enter"/>
  <button type="submit" name="btnTeste">Enviar</button>
</form>

  • but even a Ubmit button won’t work

  • Fix the code, see now

  • now that’s correct, my + 1 dice

Browser other questions tagged

You are not signed in. Login or sign up in order to post.