Yuwaz
Yuwaz

Reputation: 413

Get select tag value in tables with dynamic rows in vue.js

I want to set the value of select tag in VM data.

<table id="vm" v-cloak>
  <thead>
    <tr>
      <th>Select</th><th>Operation</th>
    </tr>
  </thead>
  <tbody>
    <tr v-for="(item, i) in rowData">
      <td>
        <select v-model="selected" @change="changeDate($event)">
          <option v-for="sItem in selectItems" :value="sItem.val">{{sItem.lbl}}</option>
        </select>
      </td>
      <td>
        <button @click="addRow(i)">+</button>
        <button @click="removeRow(i)">-</button>
      </td>
    </tr>
  </tbody>
</table>

My script

// Select tag items
const SELECT_ITEMS = [
  {val:"1", lbl:"Val1"},
  {val:"2", lbl:"Val2"},
  {val:"3", lbl:"Val3"}
];

// my vm
new Vue({
  el: "#vm",
  data:{
    rowData:[{val:"1"},{val:"2"}],
    selected : '',
    selectItems : SELECT_ITEMS
  },
  methods:{
    // add new row
    addRow(i){
      let row = {
        val : this.selected,
      };
      this.rowData.splice(i, 0, row);
      this.val = '';
    },
    // remove current row
    removeRow(i){
      this.rowData.splice(i,1);
    },
    changeDate(e){
      // I want to set a value to item in rowData.
      console.log(e.target.value);
    }
  }
});

CodePen

I do not know how to set the selected data to the data of the current row of rowData.

And, changing one changes all items.

And, I want to add selected attribute at loaded.

Upvotes: 0

Views: 4617

Answers (2)

Cloud Soh Jun Fu
Cloud Soh Jun Fu

Reputation: 1512

Why not directly use the rowData in v-model?

Demo:

<tr v-for="(item, i) in rowData">
  <td>
    <select v-model="rowData[i].val" @change="changeDate($event)">
      <option v-for="sItem in selectItems" :value="sItem.val">{{sItem.lbl}}</option>
    </select>
  </td>
  <td>
    <button @click="addRow(i)">+</button>
    <button @click="removeRow(i)">-</button>
  </td>
</tr>

Upvotes: 1

Dylan
Dylan

Reputation: 1714

Your select tags are all bound to the same variable. If you make the model a property of the rowData item, then you will get unique values per row:

change: v-model="selected" to: v-model="item.value"

pen: https://codepen.io/anon/pen/QPJqqR?editors=0001

new template:

<table id="vm" v-cloak>
  <thead>
    <tr>
      <th>Select</th><th>Operation</th>
    </tr>
  </thead>
  <tbody>
    <tr v-for="(item, i) in rowData" :key="i">
      <td>
        <select v-model="item.value" @change="changeDate($event)">
          <option v-for="sItem in selectItems" :value="sItem.val">{{sItem.lbl}}</option>
        </select>
      </td>
      <td>
        <button @click="addRow(i)">+</button>
        <button @click="removeRow(i)">-</button>
      </td>
    </tr>
  </tbody>
</table>

In this example item.value is just an option, you can use whatever property name you prefer such as item.rowName. It just has to be a property of the item object created by rowData.

Upvotes: 0

Related Questions