user13928344
user13928344

Reputation: 216

VueJS - Disable a Select Drop-down menu if there are less than 2 options

I have several select drop-downs which pull data using an Axios call. I would like the drop-downs to be disabled (greyed out) if there are fewer than 2 options left. I have managed to disable a submit button as a proof of concept but I can't get the select menu itself to disable. Maybe you cant do it this way, I'm not sure. Like most folk who post Vue questions. I'm new to Vue :) Any help would be greatly appreciated.

<div id="app">
<select v-model="quantity">
 <option disabled value="">Select</option>
  <option value="1">1</option>
  <option value="2">2</option>
   <option value="3">3</option>
   <option value="4">4</option>
  <option value="5">5</option>
   <option value="6">6</option>
</select>

 <button type="submit" :disabled="submitDisabled">Submit</button>
</div>

new Vue({
  el: '#app',
  data: {
    quantity :""
  },
  computed: {
    submitDisabled: function () {
    return this.quantity < 2 ? true : false;
    }
  }
});

Upvotes: 0

Views: 1111

Answers (1)

T J
T J

Reputation: 43156

You can use v-bind directive to bind disabled attribute of the <select> to a computed property like selectDisabled:

<select v-model="quantity" v-bind:disabled="selectDisabled">

Example:

new Vue({
  el: '#app',
  data: {
    quantity: 0,
    options: [1, 2]
  },
  computed: {
    submitDisabled: function() {
      return this.quantity < 2;
    },
    selectDisabled: function() {
      return this.options.length <= 2;
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <select v-model="quantity" :disabled="selectDisabled">
    <option disabled value="">Select</option>
    <option v-for="option in options" :value="option">{{option}}</option>
  </select>

  <button type="submit" :disabled="submitDisabled">Submit</button>
</div>

Upvotes: 1

Related Questions