2

Is it possible to have two multiple select fields, and the second select options will be filled based upon what is selected in the first select?

Explanation:

Each category has many descriptions related to them.

The main select menu is called "categories", and the options are static, they don't change. The second select menu is called "descriptions".

I can select as many categories as I want. If I select one category, the second select menu will have all descriptions related to that category as the options. When I select another category in the category select field, the descriptions related to that category will be added to the second select menu, and so on. Same goes for deselecting. I want it to be reactive.

I have found these:

https://github.com/sagalbot/vue-select https://github.com/monterail/vue-multiselect

But I haven't been able to find a solution to do this with two multiple selects yet. Any pointers?

PS. There are not too many categories and descriptions, so I can load them all into the view so vue can play around with them. I don't need an ajax call.

1 Answer 1

2

You need to populate the second select dynamically and update its data source based on events coming from the first one.

Here's a small sketch, I hope it helps.

<template>
  <div class="root">
    <!-- initial select (options hardcoded) -->
    <select v-on:change="populate($event)" multiple="multiple">
      <option value="1">One</option>
      <option value="2">Two</option>
    </select>
    <select>
      <!-- options variable is reactive -->
      <option v-for="option in options" :value="option.value">{{option.text}}</option>
    </select>
  </div>
</template>

<script>
export default {
  name: 'Selects',
  data () {
    return {
      options: []
    }
  },
  methods: {
    populate (event) {
      const options = []
      // iterate over the selected options
      // event.target.selectedOptions is a HTMLCollection 

      Array.from(event.target.selectedOptions).forEach(item => {
        // or whatever logic you need
        options.push({
          value: item.value,
          text: `You have selected ${item.text}`
        })
      })

      // update the options attribute to trigger re-rendering
      this.options = options
    }
  }
}
</script>

Later EDIT

jsfiddle here -> https://jsfiddle.net/bpgp11da/

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks a lot, will give this a try and see if I can make it work :)
Any fiddle perhaps so I can see it in action? Couldn't get it to work myself.
Added one in the main message. What's your setup?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.