What is the best way to retrieve an ID from a select multiple using Element?

I am working on a select element for assigning persons to a project. My goal is to send the ID of the selected person object to a specific function. Here is what I have tried so far:

 <el-form-item label="Assign to:" prop="person">
                <el-select v-model="form.persons"  multiple value-key="id"  id="person_id" @change="getData()" placeholder="Select Personal" class="max-input" filterable>
                  <el-option  v-for="person in orderedPersons"  
                            :label="person.name +' '+ person.last_name" 
                            :key="person.id"
                            :value="person">
                  </el-option>
                </el-select>

List of persons:

form: { persons: [],}

The Method:

getData() {
   var pid;
   this.pid = document.getElementById("person_id").value;
   console.log(pid);
  this.$axios.get("/person/hasproject/" + this.pid ).then(response => {
    try {             
      notifications_success(response.data.userMessage);
    } catch (error) {}
  });
},

The issue I am facing is that the pid (person ID) remains undefined, and I am struggling to find a solution. Any help or suggestions would be greatly appreciated.

Answer №1

When the individuals are chosen and added through the v-model, you can access their IDs by checking the this.form.persons array and iterating through it.

For example:

form: { 
 persons: [
  {name: "Alice", id: 1}, 
  {name: "Bob", id: 2}, 
  {name: "Charlie", id: 3}
 ]
}

You can then implement something like this:

getData(){  
   this.form.persons.forEach(person=>{
    this.$axios.get("/person/hasproject/" + person.id )
        .then(//continue with your logic)

   })  
}

Answer №2

The current issue you are encountering aligns with what is described in the Vue.js documentation as change detection caveats.

In Summary

Because of JavaScript's nature, Vue.js cannot automatically detect changes within objects. You need to explicitly instruct Vue.js when certain changes occur using the designated method Vue.set(object, key, value). You can experiment by implementing this approach or consider alternatives such as:

Template

 <el-form-item label="Assign to:" prop="person">
   <el-select
       multiple value-key="id"
       id="person_id"
       @change="getData()" // removed
       placeholder="Select personnel"
       class="max-input" filterable
     >
     <el-option  v-for="person in orderedPersons"  
       :label="person.name +' '+ person.last_name" 
       :key="person.id"
       :value="person.id"
       @click="updateData(person)" // added
     >
     </el-option>
  </el-select>

Script

form: { persons: []},

updateData(person) {
    for (const index in this.form.persons) {
        if (this.form.persons[i].id === person.id) {
            this.form.persons.splice(i, 1);
            // it was already inside, and we put it outside
            // the form.persons array, so we're done
            return 0;
        }
    }
    // If we are here, then person wasn't inside form.persons
    // So we add it
    this.form.persons.push(person);
    this.getDatas(person.id);
},
getData(id) {
    console.log(id);
    this.$axios.get("/person/hasproject/" + id )
    .then(response => {
      try {             
        notifications_success(response.data.userMessage);
      } catch (error) {}
  });
},

This serves as a workaround to tackle the change detection caveat problem. However, based on your intentions, it may just be the right solution for you.

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

Save and retrieve documents within an electron application

Currently, I am developing an application that will need to download image files (jpg/png) from the web via API during its initial run. These files will then be stored locally so that users can access them without requiring an internet connection in the fu ...

Steer clear of retrieving all the elements from the HTML DOM at once

Scenario I am working on a HTML5+CSS+JS slideshow project that needs to be synchronized across 50 clients in a local area network using a single wireless router. Challenge Due to the heavy content, particularly images, of the slides, I intend to dynamic ...

Exploring VueJS templating: Loading external templates

Being new to Vue.js, I have some experience with AngularJS where we used to load templates like this: template: '/sometemplate.html', controller: 'someCtrl' My question is how can we achieve something similar in Vue? Instead of embeddi ...

The use of pattern fill in fabric.js is causing a decrease in rendering speed

I recently attempted to create a clip mask effect on a large image by using the picture as a pattern and setting it to the svg paths that support the desired shape. You can view the slow-loading jsfiddle example here: http://jsfiddle.net/minzojian/xwurbw ...

Random crashes are observed in Selenium tests during the execution of JavaScript code

Currently, I am in the process of writing functional tests for a Zend application. These tests are executed using PHPUnit and a wrapper called https://github.com/chibimagic/WebDriver-PHP In order to handle the extensive use of JavaScript and AJAX in the a ...

Tracking mouse movement: calculating mouse coordinates in relation to parent element

I am facing an issue with a mousemove event listener that I have set up for a div. The purpose of this listener is to track the offset between the mouse and the top of the div using event.layerY. Within this main div, there is another nested div. The prob ...

The hamburger menu unexpectedly appears outside the visible screen area and then reappears at random intervals

My website has a hamburger menu for mobile devices, but there's a problem. When the page loads on a small screen, the hamburger menu is off to the right, causing side scrolling issues and white space. I thought it might be a CSS problem, but after exp ...

Encountering Uncaught Syntax Error when attempting a request with JSON parameters

Currently, I am using Fetch to send a post request to my server while including some additional information. Here's the code snippet: var rating = document.getElementById("rating"); var ratingValue = rating.innerHTML; fetch("/films",{ method: "po ...

The Nuxt.config.js file is responsible for rendering the noscript innerHtml element as it appears in

I've stopped JavaScript in my browser settings Incorporated inner HTML for noscript tag in nuxt.config.js Anticipated outcome is to have an iframe element added inside the body, but it's displaying text instead. How can we insert it as an eleme ...

Leverage props in Vue 3 composables

While upgrading an app from vue 2 to vue 3, I encountered some difficulties with composables. My issue revolves around using props in the composable, which doesn't seem to work as expected. The code snippet is extracted from a functioning component an ...

Can a javascript variable be accessed after loading an iframe and returning to the page?

Using a jquery plugin known as colorbox, my colorbox simply opens an iframe on the screen. This detail may not be relevant, as the core issue at hand is that I have 3 variables on my parent window that are retrieved from an AJAX call using jquery: data.re ...

Allow users to interact with table rows by making them clickable and sending a post parameter to a jQuery

After creating a table and populating it with elements using JSTL tags and EL expressions, the next step is to make each row clickable. This can be achieved by implementing the following function: $("tr").click(function() { window.location.href = $(th ...

Displaying JavaScript array contents in an HTML page without using the .innerHTML property

As someone new to the world of JavaScript and web development, I find myself faced with a challenge. I want to showcase the contents of two different JavaScript arrays in an HTML format. However, my research has led me to believe that utilizing .innerHTML ...

Developing a dynamic row that automatically scrolls horizontally

What is the best method for creating a div box containing content that automatically slides to the next one, as shown by the arrows in the picture? I know I may need jquery for this, but I'm curious if there's an alternative approach. oi62.tinyp ...

When working with Firebase, I am required to extract data from two different tables simultaneously

When working with Firebase, I have the need to extract data from tables/nodes. Specifically, I am dealing with two tables - one called jobs and the other called organisations. The outcome I am looking for: I want to retrieve all companies that do not hav ...

Prevent the SnackBar from extending to full width in case of a smaller window size

Is there a solution to prevent the SnackBar from spanning the entire width of the screen when the window is narrow? ...

React-spring is causing an increase in the number of hooks rendered compared to the previous render in React

I've encountered a similar issue as discussed on SO, but I'm struggling to resolve the problem detailed below. The scenario This code snippet found at the following link is functional: https://codesandbox.io/s/frosty-water-118xp?file=/src/App. ...

retrieving XML information into a div using Ajax and JavaScript

I am currently working on developing a chat application and facing an issue with fetching all logged in users into a div with the ID "chat_members". Despite confirming that the XML file structure is correct, the JavaScript code alongside AJAX does not seem ...

the reason behind the peculiar behavior of angularjs ng-include

I am attempting to utilize an ng-template to iterate through my args in order to create an indented menu content. Unfortunately, I have encountered issues with ng-include not working as expected. I have tried adding a quote but it still does not work. For ...

Displaying default tab content while hiding other tab content in Javascript can be achieved through a simple code implementation

I have designed tabs using the <button> element and enclosed the tab content within separate <div></div> tags like shown below: function displayTab(evt, tabName) { var i, tabcontent, tablinks; tabcontent = document.getElementsB ...