Avoid submitting form by pressing the Enter key

1

I have input in VueJS that is within form and when I press enter I do not want form to be submitted.

Together with VueJS I'm using Quasar and I was able to assign the function call only on the enter key:

<form @keydown.enter="evitarSubmit">

Function:

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

I'm having trouble finding and working out a code that overrides the effect of enter on form , but I accept suggestions ...

    
asked by anonymous 18.10.2017 / 15:05

2 answers

3

You have several ways. One is to use @keydown.enter.prevent in <form> . This prevents the submit but also prevents the enter from being used where it was pressed, and perhaps this effect is undesired.

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 to form .

new Vue({
  el: "#app",
  data() {
    return {
      input1: '',
      input2: '',
      textarea: ''
    }
  }
});
<script src="https://unpkg.com/vue/dist/vue.min.js"></script><divid="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>

Note:

There is a detail to keep in mind. Browsers behave differently when they only have 1 input. So the above method does not 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><divid="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>
    
18.10.2017 / 16:15
2

Capture the enter on your form and prevent the submit event from triggering:

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

Here's an example:

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>
    
18.10.2017 / 15:13