Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to disable value on the select option ? (vue.js 2)

My component is like this :

<div id="demo">
  <div>
    <select class="form-control" v-model="selected" required>
      <option v-for="option in options" v-bind:value="option.id">{{ option.name }}</option>
    </select>
    {{selected}}
  </div>
</div>

var demo = new Vue({
  ...
  data() {
    return {
      selected: '',
      options: [{
        id: '',
        name: 'Select Category'
      }]
    };
  },
  ...
})

See full code and demo here : https://fiddle.jshell.net/oscar11/stvct9er/5/

I want disable "Select Category". So "Select category" disabled. User can not select it. User can only choose a value other than "Select Category".

How can I do it?

like image 847
moses toh Avatar asked Feb 10 '17 21:02

moses toh


People also ask

How can I disable an option in a select based on its value in JavaScript?

querySelector('option[value="'+optionValue. replace(/["\\]/g, '\\$&')+'"]'). disabled = true; The performance depends on the number of the options (the more the options, the slower the first one) and whether you can omit the escaping (the replace call) from the second one.

How do you turn off input on Vue?

We can disable inputs conditionally with Vue 3 by setting the disabled prop to the condition when we want to disable the input. We have the input with the disabled prop set to the disabled reactive property. Below that, we have the @click directive to toggle the disabled reactive property when we click the button.

How do you conditionally disable a button in Vue?

To disable a button, we need to pass the boolean value true to the <button> element disabled attribute. We can enable it by back, by changing the isActive property value to true .

How do I turn off VUE components?

Vue Button component can be enabled/disabled by giving disabled property. To disable Vue Button component, the disabled property can be set as true .


2 Answers

You should add option directly in select tag.

<select class="form-control" v-model="selected" required>
  <option value="" disabled>Select a category</option>
  <option v-for="option in options" v-bind:value="option.id">{{ option.name }}</option>
</select>

Also, remove it from data function.

data() {
  return {
    selected: '',
    options: []
  };
}

I don't recommend you to add this option in the options array, because it is a placeholder attribute for your select.

like image 107
Mihai Alexandru-Ionut Avatar answered Oct 12 '22 23:10

Mihai Alexandru-Ionut


Other option could be to disable that element using a binding

<option v-for="option in options" 
        :disabled="!option.id"
        v-bind:value="option.id">
    {{ option.name }}
</option>
like image 29
AldoRomo88 Avatar answered Oct 12 '22 23:10

AldoRomo88