Ala Eddine Menai
Ala Eddine Menai

Reputation: 2870

How to disable button when input is empty in Vue?

I'd bind a button to input using v-bind with a function :

The code inside my template :

<template>
  <input
    type="email"
    v-model="email"
    v-bind:placeholder="$t('fields.email_place_holder')"
  />
  <input
    v-bind:disabled="{ isDisable }"
    type="submit"
    v-bind:value="$t('buttons.notify_me')"
    class="notify-me-button"
  />
</template>

The code inside my script :

  methods: {
    isDisable() {
      return email.lenght > 0;
    }
  }

But the button does not change its status , I tried to change the css style with the same way and the result is the same.The problem is that button responds once time on the first value returned by isDisable().

Upvotes: 5

Views: 22553

Answers (3)

xlm
xlm

Reputation: 7594

The button isn't disabled because the binding disabled=isDisable is not reactive.

It's not reactive because the bound value isDisable is not a reactive property (in either data or computed) and it is not a method that has any reactive parameters i.e. it's called once/evaluated to the constant false. Vue won't check if there's reactive properties in the method body, after all methods are supposed to explicitly called in your code.

There's few ways you can fix this:

  1. Make isDisable a computed property instead:
computed: {
  isDisable() {
    return this.email.length > 0;
  }
}
  1. Pass a reactive property (e.g. email) as a parameter to your method so Vue knows to update the binding.
<input
  type="submit"
  :disabled="isDisable(email)"
/>
methods: {
  isDisable(email) {
    return email.length > 0;
  }
}
  1. Directly bind a statement or condition that includes your reactive property (email). This is allowed.
<input
  type="submit"
  :disabled="email.length > 0"
/>

Working example on JS Fiddle

These would be the obvious (and perhaps idiomatic) approaches to fix this, but there are others e.g. using a watcher.

Note there's also typos in your provided code, e.g.:

  • :disabled="{isDisable}" is an not a valid binding due to the curly braces
  • isDisable(){ return email.lenght > 0 } should be length not lenght

Upvotes: 10

Daisy
Daisy

Reputation: 328

The easy way to do it is to check if the value exists or not. For example:

<input type="text" v-model="user.name" required />

For the submit button just use disable

<button type="submit" :disabled="!user.name">Submit</button>

Only when the field is filled then the submit button is enabled for submit.

Upvotes: 5

twostepdevelopers
twostepdevelopers

Reputation: 73

Try this:

<button type="button" class="btn btn-primary btn-sm ripple-surface" v- 
  bind:disabled='!isDisabled'>Save</button>
   computed: {
        isDisabled() {
        return this.categoryName.length > 0;
    }
},

Upvotes: 1

Related Questions