Rehan
Rehan

Reputation: 105

Get all Input values - Vuejs

I have multiple input elements in a simple VueJs application. But I don't have and form elements. Now I want to get all the input values at once and send to server-side [laravel] for processing?

<div>
  <input v-model="foo-bar" placeholder="edit me">
  <input v-model="bar-foo" placeholder="edit me">
  <input v-model="foo-foo" placeholder="edit me">
  <input v-model="bar-bar" placeholder="edit me">
</div>  

<div>
  <input type="button" @click="getAllData">Send</input>
</div>


getAllData(){
  // I have no idea how to get all at once!
}

Upvotes: 4

Views: 16216

Answers (3)

Rahman Rezaee
Rahman Rezaee

Reputation: 2165

<form v-on:submit.prevent="getAllData" id="frm">    
      <input name="input1" placeholder="edit me">
      <input name="input2" placeholder="edit me">
      <input name="input3" placeholder="edit me">
      <input name="input4" placeholder="edit me">
      <input type="submit" >Send</input>
</form>


<script>
   ....
   //your method parts
   methods:{
      getAllData(){
      
         let myForm = document.getElementById('frm'); 
         let formData = new FormData(myForm);
         const data = {}; 
         // need to convert it before using not with XMLHttpRequest
         for (let [key, val] of formData.entries()) {
               Object.assign(data, {[key]: val})
         }
         console.log(data);
       },
    }
   ....
<script>

Upvotes: 4

Phil
Phil

Reputation: 164871

How about you store everything in a convenient form object, eg

new Vue({
  el: '#app',
  data: {
    form: {} // create an object to hold all form values
  },
  methods: {
    getAllData() {
      console.info(this.form)
      // axios.post('/some/url', this.form)
    }
  }
})
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<div id="app">
  <div>
    <input v-model="form['foo-bar']" placeholder="edit me">
    <input v-model="form['bar-foo']" placeholder="edit me">
    <input v-model="form['foo-foo']" placeholder="edit me">
    <input v-model="form['bar-bar']" placeholder="edit me">
  </div>
  
  <div>
    <button type="button" @click="getAllData">Send</button>
  </div>
</div>

As you can see in the demo, all you need to do is reference this.form for all the values.

Upvotes: 9

Vucko
Vucko

Reputation: 20844

Bind the inputs to Vues data option:

new Vue({
  el: "#app",
  data: {
    myArray: [null, null, null, null]
  },
  methods: {
    getAllData() {
      console.log(this.myArray)

      // send to server
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <div>
    <input v-for="(arr, index) in myArray" v-model="myArray[index]" @key="index" placeholder="edit me">
  </div>

  <div>
<button type="button" @click="getAllData">Send</button>
  </div>
</div>

Upvotes: 1

Related Questions