How to dynamically populate a Vue multiple select dropdown with v-for loop?

I have been attempting to implement multi-select questions in Vue using v-for.

The Select menu and its options are populated via JSON data.

Unfortunately, I am facing difficulty in retrieving the selected results as expected.

Whenever I select an option from the 2nd menu, the selection in the 1st menu gets cleared, and vice versa for the 1st menu.

new Vue({
  el: "#app",
  data: {
    selectedValue: [],
    checklists: [
      {
   "id":1,
   "heading":"Environment",
   "deleted_at":null,
   "created_at":null,
   "updated_at":"2020-08-08T13:24:22.000000Z",
   "checklist_value":[
      {
         "id":1,
         "checklists_id":1,
         "values":"Indoor",
         "notes":null,
         "deleted_at":null,
         "created_at":"2020-08-08T13:03:50.000000Z",
         "updated_at":"2020-08-08T13:03:50.000000Z"
      },
      {
         "id":2,
         "checklists_id":1,
         "values":"Outdoor",
         "notes":null,
         "deleted_at":null,
         "created_at":"2020-08-08T13:13:27.000000Z",
         "updated_at":"2020-08-08T13:13:27.000000Z"
      }
   ]
},
{
   "id":2,
   "heading":"Location of Camera's",
   "deleted_at":null,
   "created_at":"2020-08-08T11:41:31.000000Z",
   "updated_at":"2020-08-08T13:27:59.000000Z",
   "checklist_value":[
      {
         "id":3,
         "checklists_id":2,
         "values":"Parking",
         "notes":null,
         "deleted_at":null,
         "created_at":"2020-08-08T13:28:45.000000Z",
         "updated_at":"2020-08-08T13:28:45.000000Z"
      },
      {
         "id":4,
         "checklists_id":2,
         "values":"Balcony",
         "notes":null,
         "deleted_at":null,
         "created_at":"2020-08-08T13:28:53.000000Z",
         "updated_at":"2020-08-08T13:28:53.000000Z"
      }
   ]
}

    ]
  },
  

  methods: {
    getSelectedID(event) {
      console.log(this.selectedValue);
    }
  }
  
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <div class="input-field col s12" v-for="(checklist, index) in checklists">
    <select v-model="selectedValue" @change="getSelectedID($event)" multiple="multiple">
      <option disabled>Choose options</option>
      <option v-for="(value,index) in checklist.checklist_value" :value="value.id">{{value.values}}</option>
    </select>
    <label>{{checklist.heading}}</label>
  </div>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
<script>
  $(document).ready(function() {
    $('select').formSelect();
  });

</script>

I anticipate that v-model should create a new object for the select menu, map the options as an array, and allow me to pass it to the database for saving.

Your insights on where I may have gone wrong would be greatly appreciated.

Fiddle Link: https://jsfiddle.net/dvwkz15c/

Answer №1

You keep setting the same variable whenever you update the value of your select elements because they share the same v-model. To prevent overwriting results, you should make selectedValue a nested array instead of just an array.

To fix this, add an index to each v-model so it knows which part of the selectedValue array to update when a value changes or is added.

<div class="input-field col s12" v-for="(checklist, index) in checklists">
    <select v-model="selectedValue[index]" @change="getSelectedID($event)" multiple="multiple">
    ...
</div>

Update:

I apologize for the confusion, my previous solution worked in the fiddle possibly due to version discrepancies. The new issue you're facing can be resolved by defining indices in the Vue data function like this:

<select v-model="selectedValues[index]['values']"  multiple="multiple">

and then change the array definition to an object with child arrays.

selectedValues: [
    { "values": []},
    { "values": []},
],

You can manually add this structure every time you add a checklist, or set up a mounted function in Vue that automatically creates the necessary objects within the selectedValues array based on the length of the checklists array.

Mounted Function Example

selectedValues: [],

...

mounted: function() { 
    for(let i=0; i < this.checklists.length; i ++) {
        this.selectedValues.push({
            "values": []
        });
    }
}

This will create the needed indices in the array whenever the component is mounted. Depending on how your data is loaded, you may need to wrap the for loop in

Vue.nextTick(function() { ... });
If you do this, remember to handle the scope of 'this' accordingly.

If you are fetching data via Ajax, consider placing the for loop inside a method called on mount and after the Ajax call. Since you're using push(..), reset the array before populating it again

this.selectedValues = []; ... (for loop)...

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Combining Django Templates and Vue.js

I am currently working on integrating Vue components into Django templates. The initial setup went smoothly, however, I am facing an issue with a component that requires its own import. Here is the component (vue/dropdown.html): <div id="app" ...

Tips for producing/reserving cropped images from a photo? (includes converting images to base64 format)

https://i.sstatic.net/6Nath.png Imagine having two square datasets taggedImages: { 0: {id:0, left:100, top:100, thumbSize:100, type: 'A', seasons: ['All', 'All']}, 1: {id:1, left:200, top:200, thumbSize:100, type: &apos ...

The image filter plugin is functioning properly in one project, however, it is not working in

After successfully using a plugin from w3schools to filter elements in one project, I encountered an issue when attempting to implement it in another project. Here is the link to the problematic code pen: https://codepen.io/zakero/pen/mZYBPz If anyone ca ...

Having trouble utilizing the DatePicker component in my react native application

I've encountered an issue while using DatePicker in react native. Whenever I try to use it, an error pops up saying: "render error a date or time must be specified as value prop". Here is the link to my repository: my github repository const [date, se ...

Why is it not possible to isolate the function for xmlHttp.onreadystatechange?

The JavaScript file named test.js is functioning properly when included in my HTML. function sendData() { var formData = new FormData( document.querySelector("form") ); var xmlHttp = new XMLHttpRequest(); xmlHttp.open("post", "test.php",true); ...

Exploring and cycling through numerous links using Selenium WebDriver in a node.js environment

Decided to switch from Casper.js to Selenium for access to more tools. Currently trying to loop through multiple links and navigate them using node.js along with selenium-webdriver. Struggling to find any helpful documentation or examples, as I keep enco ...

React - Image Uploader exclusively accepts images with transparent backgrounds

I need to verify if an image has a transparent background and reject it if it does, but accept it if it doesn't. However, I am facing an issue where the hasAlpha function is not triggering an 'error' alert when the image contains a backgroun ...

Send a PHP array to JavaScript to display a horizontal pop-up submenu on hover

Currently, I am engaged in the process of updating an old website. I have made modifications to the html, php, and switched from a MySQL database to an SQL database. All seems to be going well in these areas. My expertise lies in databases, PHP, SQL, and I ...

Guide to getting Material-UI Dialog up and running smoothly in your React application

I'm currently working on a project using material-UI, and I'm having trouble with the Dialog component not working properly. Despite trying various solutions, I haven't been able to get it to function correctly in my React application with m ...

Issue: The function connect.compress is not defined

I am currently working on a project that is primarily written in TypeScript and then transpiled into JavaScript. The backend is built with Node, while the frontend uses React Native. Recently, after updating to Babel6, we started encountering numerous erro ...

reveal.js: Upon a fresh installation, an error has been encountered: ReferenceError - 'navigator'

Currently, I am attempting to integrate reveal.js into my React.js/Next.js website using the instructions provided at However, upon implementation, I encountered the following error: Server Error ReferenceError: navigator is not defined This error occurr ...

Using Angular to pass an index to a pipe function

Currently, I am attempting to incorporate the *ngFor index into my pipe in the following manner: <td *ngFor="let course of courses | matchesTime:time | matchesWeekday:i ; index as i">{{course.courseName}}</td> This is how my pipe is structure ...

The enigmatic loop traversal

Can you figure out why the name property of the merged object is properly set in the code below, even though the for-loop starts with i = 1? function merge(root){ for ( var i = 1; i < arguments.length; i++ ){ for ( var key in arguments[i] ){ ...

Navigating between sibling components in Angular 1.5 using the component router

Is there a way to use the new component router in Angular 1.5 to display the sibling component alongside the main one within the ng-outlet directive? I am looking to showcase both the Detail View and the List View at the same time. Based on my understandin ...

What is the best method for establishing environment variables across different platforms?

When working with Node scripts on Windows, the format should be like this: "scripts": { "start-docs": "SET NODE_ENV=development&&babel-node ./docs/Server.js" } However, on Linux, the SET command is not used, so it would look like this: "scri ...

Is it possible to populate the blank cells in the weekday columns for previous and following months in a mat-datepicker or mat-calendar's display?

In order to enhance user experience, I am designing a calendar that allows users to select dates. My goal is to populate the empty cells at the beginning of the first week with dates from the previous and next months. For this project, I am utilizing the ...

React Bootstrap always displays tooltips

I have integrated react-bootstrap into my project. I am currently attempting to keep a tooltip always displayed, but I am facing some challenges in achieving this. Below are the approaches I have tried so far: <Card style={{width: '10rem'}} ...

Angular Fire: The $on method is missing and causing an error stating that undefined is not a function

I am currently attempting to log my Firebase data to the console, but I keep encountering an error stating undefined is not a function. Below is the full error message: TypeError: undefined is not a function at Object.childAdded (http://localhost:9000/scr ...

Displaying Images on top of Images with React/Javascript/NextJS

I have two images. Let's say image 1 is a thumbnail for news content. I would like to overlay a promotional PNG banner on top of this image and create a new output image. This output image will be used as the OG (Open Graph) image. How can I achieve t ...

What is the best way to create a smooth sliding effect using CSS?

Need help with creating a transition effect within a bordered div that reveals hidden content when a button is clicked? I'm looking to have the <a> tag displayed after clicking the button, with both the button and text sliding to the left. Here& ...