Ways to create interactive multiple dropdown menu using vue-multiselect

I'm not sure if it's possible to achieve what I want with Vue for a specific component by changing its data and automatically loading it.

Below is my expectation (tried in jQuery)

var data = {country:{type:'dropdown',values:['india','usa']},money:{type:'input',placeholder:'enter amount'},india:['Bengaluru'],usa:['Silicon Valley']}

function getDropTemplate(dropDownList){
    var dropDownStr = '';
    for(var i = 0; i < dropDownList.length; i++){
       dropDownStr += `<option value="${dropDownList[i]}">${dropDownList[i]}</option>`
    }
   return `<select class="mainCountry">${dropDownStr}</select>`;
}

function getInputTemplate(inputObj){
   return `<input type="text" placeholder="${inputObj.placeholder}"/>`
}


$(function(){
    
   $('#dropdown').on('change',function(){
      var value = $(this).val(), template = '';
      if(data[value].type == 'dropdown'){
           template += getDropTemplate(data[value].values)
      }else{
          template += getInputTemplate(data[value])
      }

      $('#selectedResults').html(template);
   });

   $(document).on('change','.mainCountry',function(){
      var result = data[$(this).val()]
      $('#subResults').html(getDropTemplate(result));
   });

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<select id="dropdown">
   <option value="">--select--</option>
   <option value="money">Money</option>
   <option value="country">Country</option>
</select>

<div id="selectedResults">

</div>

<div id="subResults">

</div>

From the snippet above, you can see that by selecting

country -> india -> Bengaluru
or
country -> usa -> Silicon Valley
.

I want to replicate the same thing with vue-multiselect

Below is what I have tried in Vue

var app = new Vue({
  el: '#app',
  components: { Multiselect: window.VueMultiselect.default },
  data () {
    return {
      value: [],
       //data:{country:{type:'dropdown',values:['india','usa']},money:{type:'input',placeholder:'enter amount'},india:['Bengaluru'],usa:['Silicon Valley']}

       options:[{name:'money'},{name:'country'}]
    }
  }
})
  <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
  <script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="aadcdfcf87c7dfc6dec3d9cfc6cfc9deea98849b849a">[email protected]</a>"></script>
  <link rel="stylesheet" href="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="285e5d4d05455d445c415b4d444d4b5c681a06190618">[email protected]</a>/dist/vue-multiselect.min.css">
  <script defer src="https://use.fontawesome.com/releases/v5.3.1/js/all.js"></script>
  
  


<div id="app">

     <multiselect
    v-model="value"
     track-by="name"
    :options="options"
    label="name"
     :multiple="false"
    :taggable="false"
  ></multiselect>
  

</div>

Answer №1

To display the interactive elements like input or multiselects, you can use conditional rendering based on the category.name.

For example, if the category.name is identified as Money, then show the text input field:

<template v-if="category && category.name === 'Money'">
  <input type="text" v-model="moneyAmount" placeholder="Enter amount">
</template>

Alternatively, when the category.name is Country, render two multiselect components (one for selecting the country and the other for region selection):

<template v-else-if="category && category.name === 'Country'">
  <multiselect
               placeholder="Select a country"
               v-model="country"
               track-by="name"
               :options="countryOptions"
               label="name"
               :multiple="false"
               :taggable="false">
  </multiselect>

  <multiselect v-if="country && country.regions"
               placeholder="Select a region"
               v-model="region"
               :options="country.regions"
               :multiple="false"
               :taggable="false">
  </multiselect>
</template>

The country selection in the multiselect dropdown is populated with options from the countryOptions[]. Each country option includes an array of regions (regions[]) to accurately display region options relevant to the selected country.

new Vue({
  data() {
    return {
      category: null,
      country: null,
      region: null,
      moneyAmount: null,
      categoryOptions: [{ name: 'Money' }, { name: 'Country' }],
      countryOptions: [
        {
          name: 'USA',
          regions: ['Silicon Valley', 'Midwest'],
        },
        {
          name: 'India',
          regions: ['Bengaluru'],
        }
      ],
    }
  },
})

Check out the demo here!

Answer №2

Would you like to display a particular component based on the option chosen from the dropdown menu?

If yes, consider utilizing a v-if directive - learn more about conditional rendering in the documentation https://v2.vuejs.org/v2/guide/conditional.html

<template v-if="country.value === 'usa'">
    // show input for USA
</template>
<template v-else-if="country.value === 'india'">
    // show input for India
</template>

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

Converting URL-esque information to JSON using JavaScript

Does anyone have a solution for converting an array of URL-like data into JSON format? For example, how can we convert the array ["a.b.c.d", "a.c.e.f", "a.b.c.g"] into the following JSON structure: items:{ text: "a", items:[ { ...

Troubleshooting problems with Window.postMessage()

When attempting to fetch data from different domains, I am facing an issue. However, if I run the code on the same server, everything works perfectly fine and I am able to retrieve the message. index.html: <head> <title>Test 1</title&g ...

Run a series of promises in an array one after the other without relying on async and await

Imagine having an array filled with promises. Each element in this array represents a knex.js query builder that is prepared to be executed and generates a promise. Is there a way to execute each element of this dynamically built array sequentially? let ...

React & Material UI: Unleashing the Power of Chained Arrow Functions

I stumbled upon this code snippet while browsing through the Material UI docs on Accordion. Despite spending hours trying to understand it, I'm still struggling to grasp its functionality: export default function CustomizedAccordions() { const [expa ...

Link Google Map Marker Click Event with Dynamic Binding

I'm currently working on binding a click event to a link that is positioned outside the Google Map Canvas. The goal is to open an "infowindow" on a map marker when this link is clicked. While I know how to achieve this for a specific point, I need a d ...

Grouping items by a key in Vue and creating a chart to visualize similarities among those keys

I am working with an object that has the following structure; { SensorA: [ { id: 122, valueA: 345, "x-axis": 123344 }, { id: 123, valueA: 125, "x-axis": 123344 }, { id: 123, valueA: 185, "x-axis": 123344 }, { ...

Step-by-step guide on incorporating an external JavaScript library into an Ionic 3 TypeScript project

As part of a project, I am tasked with creating a custom thermostat app. While I initially wanted to use Ionic for this task, I encountered some difficulty in integrating the provided API into my project. The API.js file contains all the necessary function ...

Utilizing data compression techniques to minimize network bandwidth consumption

Imagine this scenario: I have a considerable amount of data (greater than KB/MB) that needs to be transferred from an ajax request in JavaScript to a webpage in PHP. Would it be beneficial to compress the data using JS scripting before sending it to the se ...

Using scrollIntoView() in combination with Angular Material's Mat-Menu-Item does not produce the desired result

I am facing an issue with angular material and scrollIntoView({ behavior: 'smooth', block: 'start' }). My goal is to click on a mat-menu-item, which is inside an item in a mat-table, and scroll to a specific HTML tag This is my target ...

Encountering NaN while trying to retrieve the duration in JavaScript

I'm having an issue retrieving the duration of an mp4 video file when the HTML document loads. Here's my code: (function ($, root, undefined) { $(function () { 'use strict'; $(document).ready(function() { ...

What is the best way to obtain the current cursor location in draft.js?

As part of my draftjs project, I'm working on implementing a feature that allows users to easily insert links. One approach I've taken is creating a popup that appears when the shortcut cmk + k is pressed. To enhance the user experience, I am cu ...

JavaScript design not aligning

I'm currently attempting to find a pattern that includes the pipe (|) operator. Here is the code I've used to match the pattern: var format = /[ \\|]/; // This is the pattern for matching the pipe pattern if ("Near raghavendra temple ...

Creating elements in Polymer 2.0 is a breeze. Simply use the `createElement` method, then seamlessly import it using `Polymer

While working on a project, I encountered an issue where I was creating and importing an element while setting attributes with data. The code should only execute if the element hasn't been imported or created previously. However, each time I called th ...

Tips for positioning the overlay to match the icon list when hovering- JavaScript/Cascading Style Sheets (CSS)

My challenge involves a list of <li>'s accompanied by an icon that, when hovered over, displays an overlay containing information about the 'test'. The setup looks something like this: test1 test2 test3 and so forth.... Here' ...

Is there a way to transfer the chosen maximum and minimum price values to a JavaScript function within a select tag in HTML?

I have a search form that includes select options with two values. However, I want to have two select options for both the Max and Min price values. <input type="hidden" id="budget_min" name="filter_budget_min" value="0" /> <select onchange="upda ...

`AngularJS Integration in Liferay`

Utilizing AngularJS globally within Liferay Portal is a strategy I would employ. The flexibility of AngularJS allows for dynamic views in web applications, enhancing the readability and development speed of the environment. I prefer leveraging the declara ...

Refining to Showcase One Menu Selection

I am having an issue with my bootstrap menu that includes a search field. The problem is that when I try to filter the dropdown menu using the search field, it filters all dropdown items instead of just the one I want. For example, if I search for a term f ...

Verifying the invocation of a callback function through the use of $rootScope.$broadcast and $scope.$on

I have been testing to see if a callback was called in my controller. Controller (function () { 'use strict'; angular .module('GeoDashboard') .controller('CiudadCtrl', CiudadCtrl); CiudadCtrl.$i ...

When I use my loop to generate Google Map markers, the positioning is not accurate and the markers do not appear on the map. However, manually inputting the positions

There seems to be an issue with displaying Google map markers based on objects in the markers array after looping through it. I noticed that when creating a second component and setting the position manually, the marker appears correctly. However, upon ins ...