Home > Net >  How to disable button if multiple form inputs do not change in Vue.js
How to disable button if multiple form inputs do not change in Vue.js

Time:12-03

I have multiple forms created from API. For each form, I need to check if the value of inputs is changed or not; so that I can make the button disabled or enabled.

So, I tried to create a flag: isChanged: false, so that, I can make the button like this:

<v-btn
  :disabled="!isChanged"
>
  Save
</v-btn>

But, as I have multiple forms, I need to create multiple flags maybe, but I don't understand how to create multiple flags dynamically for each form.

Also, I have a Save All button which may require a new flag such as isChangedAny: false to detect if any of the multiple forms changed or not.

If any of the form inputs change, that button needs to be enabled from disabled. But, most importantly, I can't figure out how to create a method to detect if the form inputs change or not. How can I do that?

CodePen Demo

CodePudding user response:

You could create individual watchers for each form after you get the data, and store the id of changed forms:

  data: () => ({
    items: [],
    changed: []
  }),
  mounted () {
    this.getData()
    // The following code should be run in a callback when the getData() is asynchronous. 
    this.items.forEach((_, index) => {
      this.$watch(['items', index].join('.'), 
        {
          deep: true, 
          handler: (newVal, oldVal) => {
            this.changed.push(newVal.id)
          }
        }
      );
    });
  }

Then check against the changed array. If a specific id is in that array, activate the form. If the length of changed array is greater than 0, activate saveAll.

Here is the working codepen

CodePudding user response:

You essentially have two options on how to solve this:

  1. You listen to the @input event on a form field, once that fires you set a hasChanged to true. This is the easy solution but it will not work if the user changes the value back to its original, because then the hasChanged is still true and the form is still savable.
  2. Create a copy of the original form data in the mounted() hook and compare the current input with the original input through a computed property. This will work the best but might be a bit more difficult to implement.
  • Related