Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to disable button when input is empty in Vue?

Tags:

binding

vuejs2

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().

like image 414
Menai Ala Eddine - Aladdin Avatar asked Nov 18 '19 15:11

Menai Ala Eddine - Aladdin


2 Answers

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
like image 174
xlm Avatar answered Sep 18 '22 20:09

xlm


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.

like image 31
Daisy Avatar answered Sep 20 '22 20:09

Daisy