[Vuejs]-If any fields are empty the button should disable

2👍

✅

Here is what you need for this:
:disabled is a shorthand for v-bind:disabled.
And to check if a string is empty we need to take a property’s length.
e.g.
this.propertyname.length.

I am using computed prop here, it allows us to check the true/false value on the fly (by changing any of the affected properties the computed property is updated), and that is why we are using isBtnDisabled as a property (w/o parentheses – that is why it is called computed properties), and not a method/function which must be called with a parentheses.

EDITED:

I have added a shorter version in code comments (more elegant way) to check the empty fields by Boussadjra Brahim.

    <template>
      <div id="form">
        <input type="text" v-model="name" />
    
        <input type="text" v-model="fname" />
    
        <input type="text" v-model="phn" />
        <button :disabled="isBtnDisabled">Submit</button>
      </div>
    </template>
    
    <script>
    export default {
      data: function () {
        return {
          name: "",
          fname: "",
          phn: "",
        };
      },
      computed: {
        isBtnDisabled() {
          // comment; the shorter version proposed by Boussadjra Brahim
          // return !(this.name && this.fname && this.phn)
          return (
            this.name.length === 0 ||
            this.fname.length === 0 ||
            this.phn.length === 0
          );
        },
      },
    };
    </script>

2👍

Add a computed property that check if the all fields are set :

<button :disabled="isDisabled">Submit</button>

then

new Vue({
  el: '#form',
  data: {
    name: '',
    fname: '',
    phn: ''

  },
computed:{
  isDisabled(){
       return !(this.name && this.fname && this.phn)
 }
}
})

1👍

new Vue({
  el: '#form',
  data: {
    name: '',
    fname: '',
    phn: ''

  },
  methods: {},
  computed: {
    disabled(){
      return !this.name || !this.fname || !this.phn;
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="form">
    <input type="text" v-model='name'/>
    
    <input type="text" v-model='fname'/>
    
    <input type="text" v-model='phn'/>
    <button :disabled="disabled">Submit</button>
  </div>

computed may work for this kind of purpose

Leave a comment