Skip to content
Advertisement

Disable input conditionally (Vue.js)

I have an input:

<input 
  type="text" 
  id="name" 
  class="form-control" 
  name="name"  
  v-model="form.name" 
  :disabled="validated ? '' : disabled"
/>

and in my Vue.js component, I have:

..
..
ready() {
  this.form.name = this.store.name;
  this.form.validated = this.store.validated;
},
..

validated being a boolean, it can be either 0 or 1, but no matter what value is stored in the database, my input is always disabled.

I need the input to be disabled if false, otherwise it should be enabled and editable.

Update:

Doing this always enables the input (no matter I have 0 or 1 in the database):

<input 
  type="text" 
  id="name" 
  class="form-control" 
  name="name" 
  v-model="form.name" 
  :disabled="validated ? '' : disabled"
/>

Doing this always disabled the input (no matter I have 0 or 1 in the database):

<input 
  type="text" 
  id="name" 
  class="form-control" 
  name="name" 
  v-model="form.name" 
  :disabled="validated ? disabled : ''"
/>

Advertisement

Answer

To remove the disabled prop, you should set its value to false. This needs to be the boolean value for false, not the string 'false'.

So, if the value for validated is either a 1 or a 0, then conditionally set the disabled prop based off that value. E.g.:

<input type="text" :disabled="validated == 1">

Here is an example.

var app = new Vue({
  el: '#app',

  data: {
    disabled: 0
  }
}); 
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <button @click="disabled = (disabled + 1) % 2">Toggle Enable</button>
  <input type="text" :disabled="disabled == 1">
    
  <pre>{{ $data }}</pre>
</div>
Advertisement