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

What is the most effective way to dynamically incorporate external input into a SlimerJS script?

Could use some assistance with SlimerJS. My current program requires intermittent input from stdin to proceed with the next task. The code below functions effectively when using PhantomJS+CasperJS for reading external input, but encounters difficulties wi ...

Discovering the potential of utilizing an array transmitted by Node/Express on the server-side and integrating it into Google Maps on the client-side

When attempting to set up clustering markers on Google Maps, I encountered a challenge. Client-Side <script> // Code snippet from Google Map docs function initMap() { // Array of locations const locations = [ { lat: -31.56391, lng: 147.15 ...

Ways to verify the element prior to the completion of the request?

Utilizing Angular and Playwright Within my application, I have incorporated 2 buttons - one for delete mode and another for refreshing. Whenever the user triggers a refresh action, the delete mode button is disabled. Once the request returns, the delete m ...

angular ensuring seamless synchronization of objects across the application

This question pertains to both angular and javascript. In our angular app, we have numerous objects from the backend that need to remain synchronized. I am facing challenges in establishing efficient data bindings to ensure this synchronization throughout ...

Basic HTML Audio Player Featuring Several Customizable Variables

I have a unique API that manages music playback. Instead of playing audio in the browser, it is done through a Discord bot. Achievement Goal https://i.stack.imgur.com/w3WUJ.png Parameters: current: indicates the current position of the track (e.g. 2:3 ...

The Like and increment buttons seem to be unresponsive when placed within a FlatList component

Issues with the like and increment button functionality within the FlatList Here are my constructor, increment, and like functions: constructor(props){ super(props); this.state = { count: true, count1: 0, }; } onlike = () => ...

What is the best way to send information from child components to their parent in React

I'm facing a scenario where I need to increase the parent value based on actions taken in the children components. Parent Component: getInitialState :function(){ return {counter:0} }, render(){ <CallChild value={this.state.counter}/> ...

Automatically populate form fields with data from the clicked row in the HTML table when using JSP

Attempting to populate form fields using jQuery or JavaScript with row elements selected by clicking on the row. Tried a solution from Stack Overflow that didn't work as expected. I'm new to this, so please bear with me. (http://jsbin.com/rotuni/ ...

Is there a way to synchronize the autohide duration for both the LinearProgress MUI and SnackBar components?

Can someone help me align my SnackBar with the LinearProgress so that they both have an auto-hide duration of 4 seconds? I've been struggling to figure it out for hours and haven't found a solution yet. Could the issue be in the useEffect part of ...

Analyzing the HTTP status codes of various websites

This particular element is designed to fetch and display the HTTP status code for various websites using data from a file called data.json. Currently, all sites are shown as "Live" even though the second site does not exist and should ideally display statu ...

Scrolling Container Following Down the Page, Halts at Its Own Bottom (Similar to Twitter)

I am facing an issue and need some help. I am working on creating a three-column page layout where the middle section is for posts, the right section is for links and references (a bit long), and the left section is fixed. My question is: How can I preven ...

Unable to render properly after saving to Firebase

Currently, I am working on developing an express app that creates a Google map using geo coordinates extracted from photos. My goal is to utilize Firebase for storing data related to the images. While my code is functioning properly, I encountered an issue ...

Storing ajax data into a variable seems to be a challenge for me

I am facing an issue with my ajax call where I am receiving the data correctly, but I am unable to assign it to a local variable named item_price. The data that I am receiving can either be 100.00 or 115.25. Below is the snippet of my ajax code: $.ajax({ ...

Issue: "A further loader may be required to manage the output produced by these loaders."

I'm encountering an issue while developing a web page using Vue.js and webpack. The problem arises when I try to add a style in a single file component called Curry.vue, as the build process fails. <template> <div> </di ...

Accessing JS code from HTML is not possible in React

Attempting to create a list using React, I have utilized the module found here: https://github.com/pqx/react-ui-tree I am currently testing out the sample application provided in this link: https://github.com/pqx/react-ui-tree/blob/gh-pages/example/app.js ...

Guide on storing images in a designated folder using CodeIgniter

My code is located in view/admin_view2.php <?php echo form_open_multipart('home_admin/createBerita'); ?> <div class="form-group" > <label class="control-label">upload foto</label> <inpu ...

Can we dynamically add an identical DOM structure by clicking a button using jQuery?

I currently have ten text fields within a single div. I am interested in including another set of ten text fields with the same name, class, and id. Is there a way to recycle the existing DOM structure mentioned above, or will I need to generate and add t ...

How can I implement two dropdowns in jquery?

One of my dropdown menus is currently utilizing this code to fetch the selected value: $(document).on('change','#DropDown1',function() { var value1 = $(this).children("option:selected").val(); var data = {"key": value1}; ...

The comparison between importing TypeScript and ES2015 modules

I am currently facing an issue with TypeScript not recognizing the "default export" of react. Previously, in my JavaScript files, I used: import React from 'react'; import ReactDOM from 'react-dom'; However, in TypeScript, I found tha ...

How to change the image source using jQuery when hovering over a div and set its class to active?

I am working with a div structure that looks like this: <div class="row margin-bottom-20"> <div class="col-md-3 service-box-v1" id="div1"> <div><a href="#"><img src="path" id="img1" /></a></div> ...