Home > Back-end >  Vue - Disable dropdown if other dropdown is selected
Vue - Disable dropdown if other dropdown is selected

Time:07-05

I have two dropdown menus and I want the user to only be able to select an option if the other is not selected. I'm converting from Razor pages to Vue so I need to do it in Vue.

This is what the Razor page looks like: Razor

And this is what the Vue page I made currently looks like: enter image description here

I've got it to sort of work - but I just want it to be temporarily disabled if one of the dropdowns is selected, not removed entirely. Here's the fiddle

CodePudding user response:

If I'm not wrong the example below will solve the problem. Also check here for demo

You can feel free to make selection from both dropdowns. If one is selected other one will be deselected.

<template>
  <select @change="changeHandler('one')" v-model="one"  >
    <option v-for="subject in subjects">
      {{ subject }}
    </option>
  </select>
  <select @change="changeHandler('two')" v-model="two" >
    <option v-for="subject in subjects">
      {{ subject }}
    </option>
  </select>
  
  <div>
    Selected: {{one}} {{two}}
  </div>
</template>

<script>
export default {
  data() {
    return {
      subjects: [
        "Education",
        "Economics",
        "English",
        "English & Creative Writing",
        "French",
        "History",  
        "Law",
        "Marketing",
        "Mathematics",  
        "Psychology", 
        "Spanish"
      ],
      one: "",
      two: "",
    }
  },
  methods: {
    changeHandler(param) {
      if(param === 'one') {
        this.two = "";
      } else {
        this.one = ""
      }
    }
  }
}
</script>

CodePudding user response:

Instead of using v-if you can use select's disable attribute or conditional class binding. Here is a codesandbox example

<select v-model="one" :disabled="!!two">
      <option v-for="(subject, index) in subjects" :key="index">
        {{ subject }}
      </option>
</select>
  • Related