Home > Software design >  multiple select box using v-for
multiple select box using v-for

Time:01-25

I have multiple select boxes which are rendered using a v-for loop, what I am trying to do is to store each option value for each select box in an array but when I select an option it only stores the chosen option, not multiple options

 <template v-for="(gettailor) in gettailors" :key="gettailor.id">

                      <div  >
                           <div  >
                                 <p>{{ gettailor.names }}</p>
                            </div>




                      </div>



                      <div >
                        <div >
                            <select    id="tailors"  v-model="tailors"   required>

                                <template v-for="(item) in gettailor.tailor" :key="item.id">

                                <option :value="item.id">{{ item.tailor }}</option>

                                </template>
                            </select>

                            <label for="tailors">Choose {{ gettailor.names }}</label>
                        </div>

                      </div>




                    </template>

    <script>
  import { ref, watch,onMounted } from 'vue';
 const tailors = ref([]);

   </script>

CodePudding user response:

I think tailors should be an object, then you bind the select value to a value in the object:

<select
  
  id="tailors[]"            <-------- generates several selects with same id 
  v-model="tailors[gettailor.id]"  <--------- bind to object value
  required
>

Of course you can also use an array, but it does not work well with reactivity if you use loop index as key (if order changes, you don't know where the values came from), and if you use tailor id, you get a sparse array, which is probably hard to work with.

  • Related