Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable second input when first is filled in Vue

Tags:

vue.js

I have a form, with two input fields.

How do I disable the alternate field when one is filled? For example, both fields start as being enabled. But, when I enter something in field 1, field 2 should be disabled, and vice versa -- so the user can only use one of the fields, not both at the same time.

In jQuery, I used the keyup event, and checked the length (> 0) of the field that generated the event, and disabled the other field. Similarly, for the other field. In Vue, I don't know how to reference another field, to disable it with :disable="true".

like image 829
farhany Avatar asked Oct 20 '25 06:10

farhany


2 Answers

Something like this should work:

<input type="text" v-model="firstField" :disabled="!!secondField" />
<input type="text" v-model="secondField" :disabled="!!firstField" />

This assumes that you have a data attribute for both firstField and secondField.

like image 81
John Ellmore Avatar answered Oct 21 '25 21:10

John Ellmore


Take a look

<div id="app">
   <input type="text" v-model="text1" :disabled="shouldDisable1" @keyup="disable('second')">
  <input type="text" v-model="text2" :disabled="shouldDisable2" @keyup="disable('first')">
</div>

new Vue({
  el: "#app",
  data: {
    text1: '',
    text2: '',
    shouldDisable1: false,
    shouldDisable2: false
  },
    methods: {
    disable(input) {
        if(input == 'first') {
        this.shouldDisable1 = true
        if (this.text2 == '') this.shouldDisable1 = false
      }else {
        this.shouldDisable2 = true
        if (this.text1 == '') this.shouldDisable2 = false
      }
    }
  }
})

See it in action in jsfiddle

like image 41
Roland Avatar answered Oct 21 '25 21:10

Roland



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!