Disable input conditionally (Vue.js)
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>
you could have a computed property that returns a boolean dependent on whatever criteria you need.
<input type="text" :disabled=isDisabled>
then put your logic in a computed property...
computed: {
isDisabled() {
// evaluate whatever you need to determine disabled here...
return this.form.validated;
}
}
Not difficult, check this.
<button @click="disabled = !disabled">Toggle Enable</button>
<input type="text" id="name" class="form-control" name="name" v-model="form.name" :disabled="disabled">
jsfiddle
Your disabled attribute requires a boolean value:
<input :disabled="validated" />
Notice how i've only checked if validated
- This should work as 0 is falsey
...e.g
0 is considered to be false in JS (like undefined or null)
1 is in fact considered to be true
To be extra careful try:
<input :disabled="!!validated" />
This double negation turns the falsey
or truthy
value of 0
or 1
to false
or true
don't believe me? go into your console and type !!0
or !!1
:-)
Also, to make sure your number 1
or 0
are definitely coming through as a Number and not the String '1'
or '0'
pre-pend the value you are checking with a +
e.g <input :disabled="!!+validated"/>
this turns a string of a number into a Number e.g
+1 = 1
+'1' = 1
Like David Morrow said above you could put your conditional logic into a method - this gives you more readable code - just return out of the method the condition you wish to check.