Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically create select options on the fly

I have 2 selects, one with data and other one empty. When first one is selected, I catch it using a switch. Now, depending on the value, I want to create option elements and put them inside empty select.

Let's say I have an array of values

var values = ['Hello', 'world', 'etc']

When selected

selected(event) {
  var name;
  switch (event.target.value) {
    case 'roth':
       // append values as options into select, using foreach
       // such as:
       // <option value="hello">Hello</option>
    ...
  }
}

This is select in my template:

<select class="form-control" :id="selection">
    <option selected="" disabled="" value="0"></option>
</select>
like image 504
senty Avatar asked Jul 26 '26 22:07

senty


1 Answers

You can just define an empty array for options for second select, and push values with your switch/case. Later you can use that values with v-for For example:

new Vue({
  el: '#app',
  data: {
    selectValues: ['Hello', 'world', 'etc'],
    secondarySelectValues: [],
  },
  methods: {
    handleChange: function(e) {
      switch (e.target.value) {
        case 'Hello':
          this.secondarySelectValues = [];
          this.secondarySelectValues.push('this', 'is', 'hello');
          break;
        case 'world':
          this.secondarySelectValues = [];
          this.secondarySelectValues.push('this', 'is', 'world')
          break;
        case 'etc':
          this.secondarySelectValues = [];
          this.secondarySelectValues.push('this', 'is', 'etc')
          break;
      }
    }
  }
})
<script src="https://unpkg.com/[email protected]"></script>
<div id="app">

  <select class="form-control" @change="handleChange">
    <option v-for="selectValue in selectValues" :value="selectValue">{{ selectValue }}</option>
  </select>

  <select class="form-control secondary">
    <option v-for="secondarySelectValue in secondarySelectValues" :value="secondarySelectValue">{{ secondarySelectValue }}</option>
  </select>

</div>
like image 106
Narek-T Avatar answered Jul 30 '26 04:07

Narek-T