Using Vue.js to easily move objects between two selection elements

Below is the HTML code that includes 2 select elements and 2 buttons for transferring options between them:

<div class="col-xs-1" style="width:45%">
    <label for="txtDescricao">Motivos</label>
    <select multiple="multiple" class="form-control" id="todosMotivos" v-model="Motivos_selected" style="width: 100%;">
        <option v-for="motivo in Motivos" v-bind:value="motivo.Codigo">{{motivo.Descricao}}</option>
    </select>
</div>
<div class="col-xs-1 text-center align-middle" style="width:10%">
    <br />
    <p><button type="button" class="btn btn-default btn-sm fa fa-arrow-right" v-on:click.prevent="adicionarItensSelect"></button></p>
    <p><button type="button" class="btn btn-default btn-sm fa fa-arrow-left" v-on:click.prevent="removerItensSelect"></button></p>
</div>
<div class="col-xs-1" style="width:45%">
    <label for="txtDescricao">Motivos vinculados</label>
    <select multiple="multiple" class="form-control" id="selectedMotivos" v-model="Motivos_vinculados_selected" style="width: 100%;">
        <option v-for="motivo in Motivos_vinculados" v-bind:value="motivo.Codigo">{{motivo.Descricao}}</option>
    </select>
</div>

The following Vue app data variables are defined:

Motivos: [],
Motivos_selected: [],
Motivos_vinculados: [],
Motivos_vinculados_selected: [],

To populate the "Motivos" list, the function getMotivos() is used:

getMotivos: function (motivosVinculados) {
    var self = this;

    $.ajax({
        type: "POST",
        url: "../Motivo/GetMotivos",

        success: function (data) {
            self.Motivos = data.motivos;
        },
        error: function (error) {
            console.log(error);
            alert('Erro ao executar operação.');
        }
    });
},

When trying to transfer selected options to the second select element using adicionarItensSelect(), the issue arises:

adicionarItensSelect: function () {
    var self = this;
    self.Motivos_vinculados.push(self.Motivos_selected);
},

Unfortunately, the option appears blank in the second select. It seems like the object is not being transferred properly. How can I resolve this?

Answer №1

Make sure to connect the object with the options in this manner:

<option v-for="reason in Reasons" v-bind:value="reason>{{motivo.Description}}</option>

var appEquipment = new Vue({
    el: "#equipmentApp",
    data: {
        Reasons: [
        { Code: 1, Description: "Reason 1" },
        { Code: 2, Description: "Reason 2" },
          { Code: 3, Description: "Reason 3" }
        ],
        Reasons_selected: [],
        Linked_reasons: [],
        Linked_reasons_selected: []
    },
    methods: {
        addItemsSelect: function () {
            var self = this;
            self.Linked_reasons = self.Linked_reasons.concat(self.Reasons_selected);
        }
    }
});
<script src="https://unpkg.com/vue"></script>
<section id="equipmentApp" class="content">
<div class="col-xs-1" style="width:45%">
    <label for="txtDescription">Reasons</label>
    <select multiple="multiple" class="form-control" id="allReasons" v-model="Reasons_selected" style="width: 100%;">
        <option v-for="reason in Reasons" v-bind:value="reason">{{reason.Description}}</option>
    </select>
</div>
<div class="col-xs-1 text-center align-middle" style="width:10%">
    <br />
    <p><button type="button" class="btn btn-default btn-sm fa fa-arrow-right" v-on:click.prevent="addItemsSelect"> -> </button></p>
    <p><button type="button" class="btn btn-default btn-sm fa fa-arrow-left" v-on:click.prevent="removeItemsSelect"> <- </button></p>
</div>
<div class="col-xs-1" style="width:45%">
    <label for="txtDescription">Linked reasons</label>
    <select multiple="multiple" class="form-control" id="selectedReasons" v-model="Linked_reasons_selected" style="width: 100%;">
        <option v-for="reason in Linked_reasons" v-bind:value="reason.Code">{{reason.Description}}</option>
    </select>
</div>
</section>

Hope this solution works for you :)

Answer №2

It appears that you are inserting the entire Motivos_selected array into the Motivos_vinculados array, creating a nested array.

A better approach would be to use:

self.Motivos_vinculados.concat(self.Motivos_selected);

If you wish to merge the two arrays, you can overwrite the entire array like this:

self.Motivos_vinculados = self.Motivos_selected;

Alternatively, you could iterate through the first array and push each item to the second array:

self.Motivos_vinculados.map(item => { self.Motivos_selected.push(item) });

EDIT--------- After reviewing the fiddle, I came up with the following solution:

adicionarItensSelect: function () {
    var self = this;
    self.Motivos_vinculados = this.Motivos.filter(motivo => {
        return self.Motivos_selected.indexOf(motivo.Codigo) !== -1;
    });

}

I hope this explanation is helpful!

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

Is there a way to send a JSON object and a file to an ASP.NET server using the fetch method?

I'm facing a challenge here, as I attempt to send a json object from my indexedDb along with an IFormFile object to the server at the same time. The method that handles this scenario is structured like so: [HttpPost] public async Task<IActionR ...

Using Jquery's append() method to dynamically alter the HTML content

I am attempting to create a table with rows that are added dynamically. The challenge I am encountering is that each row consists of form elements, including multiple inputs. I have a PHP function that generates the correct row, and I have been able to sen ...

When a node sends a request to an endpoint, it receives a response from

In my project, I have a file named "forms.routes.js" which contains a variety of endpoints using router.get, router.post, router.put, and router.delete. Interestingly, when I try to access the 16th endpoint in the list: localhost:3000/v2/forms/:domain/co ...

What is the best way to optimize a search for objects with extensive field arrays?

Recently, I've been working with an object schema that includes an array field to store ids for objects from a separate collection. This array has the potential to contain thousands of ids. Up until now, I have been excluding this field using .select( ...

Tips on utilizing Sinon for mocking a function that triggers a REST request

I'm currently navigating my way through sinon and mocha, working on the code and test provided below. My goal is to test the findAll() method without triggering an http request. However, I've encountered an error with the current setup: [TypeErr ...

Searching in Vue based on the selected option is only possible by the selected criteria and not by id, regardless of the

#1 Even if chosen, cannot search by id. The 'name' condition in the loop works well but I am unable to correctly search by id (returns nothing). #2 When selecting an option from the dropdown menu, it only displays until I start typing. I would l ...

Why is ui-view failing to display the associated template in angular-ui-tab?

Can someone help me troubleshoot why ui-view is not working for ui-tab in my code? Here is what I am experiencing: On the customers page, I have a link that redirects to the update customer page when clicked. The link looks like this: http://localhost:300 ...

Can the value of a variable be passed as seen in the JavaScript code snippet?

I'm wondering if I'm on the right track with generating random colors when a button is clicked. Here's my code: randomColor = "#" + Math.floor(Math.random() * 16777215).toString(16); // --- more code --- changeHeaderColor() { con ...

An error occurred with redirecting using jQuery Mobile's new method in version 1.5

Utilizing jQuery Mobile for its history state feature, I am looking to redirect users to another "page" using the jQuery method recommended in their latest documentation. p/s: I prefer the jQuery navigation method due to the hashchange/history support and ...

The tooltip menu options in material ui are displaying in a different location in the window rather than below the button icon. How can this issue be resolved?

I'm having trouble implementing a tooltip on an option menu icon and it's not working as expected. Here is my code: export default function FadeMenu() { const [ anchorEl, setAnchorEl ] = React.useState(null) const bus = Bus() const o ...

What is the best way to change the background color for my photo gallery?

I'm currently working on a project to create a unique photo gallery where each image has a different colored background. I have six images in total, but right now all of them have a pink background. I've attempted adding another .popup class in t ...

What is the reason that server.js is always excluded from the Webpack build process?

I am currently utilizing Vue.js 3 for the front end of my application, while employing Node/Express for the back-end. My goal is to implement server side rendering, but I have encountered some challenges along the way. As far as I can tell, the client-sid ...

Trouble with implementing Ajax in Express and jquery

My app has a browse page where users can add items as owned or wanted. Currently, when adding an item it redirects back to the general /browse page. However, I want the page to not refresh at all. I'm attempting to achieve this with ajax, but as a beg ...

Prevent additional clicks on the image

Currently, I am dealing with a situation where I have a list containing a jQuery handler for mouse clicks. The dilemma is that I need to insert an image into the list, but I want clicking on the image to trigger a different function than clicking elsewhere ...

Leveraging the "dialogclose" event within jQuery Mobile

Is there a way to change an image once it is clicked and change back when the dialog it links to is closed? I found a potential solution on this site, but after modifying it for my needs, it doesn't seem to work. Can anyone help me figure out what I a ...

Utilize the existing code to prevent multiple form submissions

My current focus is on integrating a Delete Account feature into my website. If a user requests to delete their account (please note that it takes 3 days to completely delete the data) and tries to log in within this 3-day period, we need to prompt for co ...

When using Ajax in Jquery and expecting data of type JSON, the response always seems

Looking to create a basic jQuery Ajax script that checks a user's discount code when the "Check Discount Code" button is clicked? Check out this prototype: <script> jQuery(function($) { $("#btn-check-discount").click(function() { c ...

Error: Unable to access the 'length' property of an undefined value | Solving the challenge of finding the shortest word within a string | Codewars Problem

I'm currently working on a function to find the shortest word in a given string of words. Issue: I encountered the error below TypeError: Cannot read property 'length' of undefined at findShort at Test.describe._ at /runner/fra ...

Guidelines for queuing method calls using Vue.js

Is there a way to invoke a method using a queue system? Imagine having a method that makes API calls and can only handle 3 calls at once. If more than 3 calls are made from a component, the remaining ones should wait until one call finishes before proceedi ...

Is it possible to incorporate jQuery into an AngularJS project?

When it comes to testing, AngularJS is a framework that supports test-driven development. However, jQuery does not follow this approach. Is it acceptable to use jQuery within Angular directives or anywhere in AngularJS for manipulating the DOM? This dilemm ...