Search code examples
javascriptvue.jsvuejs2vue-componentv-select

How can I add items to an input using the enter key and only submit the form when i click a button?


I'm using v-select and there is a problem with this plugin... When you press enter inside input, it submit to form. How can i add items to input using Enter and only submit the form when i click at Button?

Example Here CODE PEN

HTML

<div id="app">
  <h1>Vue Select</h1>
  <p>Try to add items in input using "ENTER"</p>
  <form v-on:submit.prevent="submited()">
  <v-select multiselect :options="options"></v-select>
    <button type="submit">Submit</button>
  </form>
</div>

JS

Vue.component('v-select', VueSelect.VueSelect)

new Vue({
  el: '#app',
  data: {
    options: ["some", "thing", "another", "things"]
  },
  methods: {
    submited(){
      alert('submited!')
    }
  }
})

Thanks!!


Solution

  • I would prevent default on the form and then move the submitted logic to the button.

    Vue.component('v-select', VueSelect.VueSelect)
    
    new Vue({
      el: '#app',
      data: {
        options: ["some", "thing", "another", "things"]
      },
      methods: {
        submitted() {
          console.log('submited!')
        }
      }
    })
    body {
      font-family: 'Open Sans', sans-serif;
    }
    
    #app {
      max-width: 35em;
      margin: 1em auto;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.4/vue.min.js"></script>
    <script src="https://unpkg.com/[email protected]/dist/vue-select.js"></script>
    <div id="app">
      <h1>Vue Select</h1>
      <p>Try to add items in input using "ENTER"</p>
      <form v-on:submit.prevent="">
        <v-select multiple :options="options"></v-select>
        <button type="button" v-on:click="submitted()">Submit</button>
      </form>
    </div>

    See here: https://codepen.io/uidan/pen/PJjOyb