Disable input conditionally (Vue.js)

JavascriptHtmlFormsvue.jsInput

Javascript Problem Overview


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 : ''"
/>

Javascript Solutions


Solution 1 - Javascript

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>

Solution 2 - Javascript

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;
  }
}

Solution 3 - Javascript

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

Solution 4 - Javascript

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

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.

Solution 5 - Javascript

You can manipulate :disabled attribute in vue.js.

It will accept a boolean, if it's true, then the input gets disabled, otherwise it will be enabled...

Something like structured like below in your case for example:

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

Also read this below:

>

Conditionally Disabling Input Elements via JavaScript > Expression
You can conditionally disable input elements inline > with a JavaScript expression. This compact approach provides a quick > way to apply simple conditional logic. For example, if you only needed > to check the length of the password, you may consider doing something > like this.

<h3>Change Your Password</h3>
<div class="form-group">
  <label for="newPassword">Please choose a new password</label>
  <input type="password" class="form-control" id="newPassword" placeholder="Password" v-model="newPassword">
</div>

<div class="form-group">
  <label for="confirmPassword">Please confirm your new password</label>
  <input type="password" class="form-control" id="confirmPassword" placeholder="Password" v-model="confirmPassword" v-bind:disabled="newPassword.length === 0 ? true : false">
</div>

Solution 6 - Javascript

You may make a computed property and enable/disable any form type according to its value.

<template>
    <button class="btn btn-default" :disabled="clickable">Click me</button>
</template>
<script>
     export default{
          computed: {
              clickable() {
                  // if something
                  return true;
              }
          }
     }
</script>

Solution 7 - Javascript

Try this

 <div id="app">
  <p>
    <label for='terms'>
      <input id='terms' type='checkbox' v-model='terms' /> Click me to enable
    </label>
  </p>
  <input :disabled='isDisabled'></input>
</div>

vue js

new Vue({
  el: '#app',
  data: {
  	terms: false
  },
  computed: {
  	isDisabled: function(){
    	return !this.terms;
    }
  }
})
   

Solution 8 - Javascript

To toggle the input's disabled attribute was surprisingly complex. The issue for me was twofold:

(1) Remember: the input's "disabled" attribute is NOT a Boolean attribute.
The mere presence of the attribute means that the input is disabled.

However, the Vue.js creators have prepared this... https://vuejs.org/v2/guide/syntax.html#Attributes

(Thanks to @connexo for this... https://stackoverflow.com/questions/49194163/how-to-add-disabled-attribute-in-input-text-in-vuejs/49194596#49194596)

(2) In addition, there was a DOM timing re-rendering issue that I was having. The DOM was not updating when I tried to toggle back.

Upon certain situations, "the component will not re-render immediately. It will update in the next 'tick.'"

From Vue.js docs: https://vuejs.org/v2/guide/reactivity.html

The solution was to use:

this.$nextTick(()=>{
	this.disableInputBool = true
})

Fuller example workflow:

<div @click="allowInputOverwrite">
	<input
		type="text"
		:disabled="disableInputBool">
</div>

<button @click="disallowInputOverwrite">
	press me (do stuff in method, then disable input bool again)
</button>

<script>

export default {
  data() {
    return {
      disableInputBool: true
    }
  },
  methods: {
    allowInputOverwrite(){
      this.disableInputBool = false
    },
    disallowInputOverwrite(){
	  // accomplish other stuff here.
      this.$nextTick(()=>{
        this.disableInputBool = true
      })
    }
  }

}
</script>

Solution 9 - Javascript

Can use this add condition.

  <el-form-item :label="Amount ($)" style="width:100%"  >
            <template slot-scope="scoped">
            <el-input-number v-model="listQuery.refAmount" :disabled="(rowData.status !== 1 ) === true" ></el-input-number>
            </template>
          </el-form-item>

Solution 10 - Javascript

This will also work

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

Solution 11 - Javascript

If you use SFC and want a minimal example for this case, this would be how you can use it:

export default { data() { return { disableInput: false } }, methods: { toggleInput() { this.disableInput = !this.disableInput } } }

Clicking the button triggers the toggleInput function and simply switches the state of disableInput with this.disableInput = !this.disableInput.

Solution 12 - Javascript

Bear in mind that ES6 Sets/Maps don't appear to be reactive as far as i can tell, at time of writing.

Solution 13 - Javascript

My Solution:

// App.vue Template:

<button
            type="submit"
            class="disabled:opacity-50 w-full px-3 py-4 text-white bg-indigo-500 rounded-md focus:bg-indigo-600 focus:outline-none"
            :disabled="isButtonDisabled()"
            @click="sendIdentity()"
          >
            <span v-if="MYVARIABLE > 0"> Add {{ MYVARIABLE }}</span>
            <span v-else-if="MYVARIABLE == 0">Alternative text if you like</span>
            <span v-else>Alternative text if you like</span>
          </button>

Styles based on Tailwind

// App.vue Script:

 (...)
  methods: {
   isButtonDisabled(){
    return this.MYVARIABLE >= 0 ? undefined: 'disabled';
   }
 }

Manual: vue v2 vue v3

> If isButtonDisabled has the value of null, undefined, or false, the > disabled attribute will not even be included in the rendered

Solution 14 - Javascript

We can disable inputs conditionally with Vue 3 by setting the disabled prop to the condition when we want to disable the input

For instance, we can write:

<template>
  <input :disabled="disabled" />
  <button @click="disabled = !disabled">toggle disable</button>
</template>


<script>
export default {
  name: "App",
  data() {
    return {
      disabled: false,
    };
  },
};
</script>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionZaffar SaffeeView Question on Stackoverflow
Solution 1 - JavascriptasemahleView Answer on Stackoverflow
Solution 2 - JavascriptDavid MorrowView Answer on Stackoverflow
Solution 3 - JavascriptMarcos DantasView Answer on Stackoverflow
Solution 4 - JavascriptFrancis LeighView Answer on Stackoverflow
Solution 5 - JavascriptAlirezaView Answer on Stackoverflow
Solution 6 - JavascriptYamen AshrafView Answer on Stackoverflow
Solution 7 - JavascriptAtchutha rama reddy KarriView Answer on Stackoverflow
Solution 8 - JavascriptKobiView Answer on Stackoverflow
Solution 9 - JavascriptansonView Answer on Stackoverflow
Solution 10 - JavascriptAYKView Answer on Stackoverflow
Solution 11 - JavascriptStevenSiebertView Answer on Stackoverflow
Solution 12 - JavascriptomarjebariView Answer on Stackoverflow
Solution 13 - JavascriptJulianView Answer on Stackoverflow
Solution 14 - JavascriptYogesh WaghmareView Answer on Stackoverflow