Skip to content
Advertisement

How to create dynamic two relational dropdown in Vuejs

I am new to . I’m stuck trying to dynamically set the options of one select based on the selected value in another.

For example, I have two dropdowns named division and district.

var A = [{1: 'a'},{2:'b'}];

If value of A is 1, then the district select should load the related codes. I can do it with jQuery but not with Vue.

Here is my template.

<div class="form-group" :class="class_obj">
  <select name="div_code" v-model="div_code" class="form-control" required>
    <option value="">Choose One</option>
    <option v-for="option in div_list" v-bind:value="option.value">
      {{ option.text }}
     </option>
   </select>
  </div>

  <div class="form-group" :class="class_label">
    <label for="">District</label>
   </div>
   <div class="form-group" :class="class_obj">
     <select name="dist_code" v-model="dist_code" class="form-control" required>
       <option value="">Choose One</option>
     </select>
    </div>

Here is my javascript.

export default {
   data():{
     div_list: [
       {'1': "ABC"} , {'2': "DEF"}
     ];
   }
}

How can I load the dist_code select with related data from ajax when div_code value is 1?

Advertisement

Answer

Handle a change event on the div_code change

<select name="div_code" 
        v-model="div_code" 
        @change="onDivCodeChange"
        class="form-control" 
        required>
  <option value="">Choose One</option>
  <option v-for="option in div_list" v-bind:value="option.value">
    {{ option.text }}
  </option>
</select>

And add the onDivCodeChange method to your Vue.

methods:{
  onCodeChange(){
    // make an ajax call and set the options for your
    // dist_code here. For example:
    $.ajax({
      url: "...",
      data: {div_code: this.div_code},
      success: codes => this.code_list = codes
      error: err => console.log(err)
    })
  }
}

And of course add code_list as a property of your data and update your template.

<select name="dist_code" v-model="dist_code" class="form-control" required>
  <option value="">Choose One</option>
  <option v-for="code in code_list" :value="code.value">{{code.text}}</option>
</select>
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement