Home > Software engineering >  How to loop checkbox for each value in dropdown list in vuejs?
How to loop checkbox for each value in dropdown list in vuejs?

Time:10-13

data() {
    return {
      selected: [],
    }
    watch: {
      selected(val) {
        this.$emit("checked", val);
      },
    },
<div class="dropdown">
  <span>State:</span>
  <select :disabled="listCities.length == 0" v-model="selectedCity">
    <option value="">Select a City</option>
    <option v-for="(city, index) in listCities" :key="index" :value="city.city_name">
      {{ city.city_name }}
      //<input type="checkbox" :id="index" :value="city.city_name" v-model="selected" />
    </option>
  </select>
</div>

How to loop checkbox for each value in dropdown list in vuejs?

Basically i have a dropdown, where i can able to select list of cities available based on the state. So, Once i get the cities, i should be able to select multiple of them and display the number of selected cities.(by placing checkboxes for each value from city dropdown list, and display the number of selected cities)

Codesandbox link working:-https://codesandbox.io/s/xenodochial-bush-yxfc8?file=/src/App.vue

CodePudding user response:

One way:

new Vue({
  el: '#demo',
  data() {
    return {
      listCities: [{city_name: 'name 1'}, {city_name: 'name 2'}, {city_name: 'name 3'}, {city_name: 'name 4'}, {city_name: 'name 5'}, {city_name: 'name 6'}],
      selectedCity: []
    }
  },
  methods: {
    selectCity(city) {
      this.selectedCity.includes(city) ? this.selectedCity = this.selectedCity.filter(s => s !== city) : this.selectedCity.push(city)
    },
  }
})

Vue.config.productionTip = false
Vue.config.devtools = false
.city__list {
  list-style: none;
  height: 50px;
  width: 150px;
  overflow: auto;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="demo" class="dropdown">
  <span>Cities:</span>
  <ul class="city__list">
    <li v-for="(city, index) in listCities" :key="index" >
      <input id="chk" type="checkbox" :value="city.city_name" @click="selectCity(city.city_name)" />
      {{ city.city_name }}
    </li>
  </ul>
  <span>Selected Cities:</span>
  <p>{{ selectedCity }}</p>
</div>

  • Related