farhany
farhany

Reputation: 1541

Disable second input when first is filled in Vue

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".

Upvotes: 4

Views: 1105

Answers (2)

Roland
Roland

Reputation: 27789

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

Upvotes: 2

John Ellmore
John Ellmore

Reputation: 2229

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.

Upvotes: 4

Related Questions