Disabling a button in Vue.js when form inputs remain unchanged

I am facing a challenge with multiple forms that were created from an API. I need to constantly monitor if the input values within each form have been changed in order to toggle the button between disabled and enabled states.

To address this issue, I attempted to create a single flag: isChanged: false. This allowed me to control the button like this:

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

However, dealing with multiple forms means I might need to generate multiple flags dynamically for each form. Unfortunately, I am unsure of how to achieve this efficiently.

In addition, there is a Save All button which could require a new flag like isChangedAny: false to determine whether any of the forms have been altered or not.

If any input value within a form changes, the 'Save All' button should transition from a disabled state to an enabled one. Yet, my main struggle lies in developing a method to accurately detect these changes in the form inputs. Can someone guide me on this?

Check out the CodePen Demo here

Answer №1

To effectively manage changes in multiple forms, a solution is to create individual watchers for each form after retrieving the data. These watchers will track any modifications and store the IDs of the changed forms:

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

After capturing the changes in the changed array, it's possible to check if a specific ID exists within this array. If a matching ID is found, the corresponding form can then be activated. Moreover, by checking if the changed array has a length greater than 0, it becomes feasible to activate the saveAll feature.

For a practical demonstration, refer to the following functional CodePen demo.

Answer №2

To tackle this issue, you have two main approaches:

  1. One option is to monitor the @input event on a form field, setting a flag to hasChanged once triggered. While simple, this method may not be foolproof as it won't detect if the user reverts the value back to its original state.
  2. Alternatively, another approach involves creating a duplicate of the initial form data within the mounted() hook and leveraging a computed property to compare the current input with the original data. Although more complex to implement, this second solution is likely more robust in maintaining form integrity.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Manipulate Angular tabs by utilizing dropdown selection

In my latest project, I have developed a tab component that allows users to add multiple tabs. Each tab contains specific information that is displayed when the tab header is clicked. So far, this functionality is working perfectly without any issues. Now ...

Send information to the webpage through both GET and POST methods

Can data be submitted to the same page using both the GET and POST methods? Certain sensitive information needs to be sent via POST, while other data such as page_number and search_phrase should be submitted with GET. I attempted creating two forms, one ...

In TypeScript, a subclass can be assigned as a value of a superclass-type, but it cannot be directly used as a parameter in a function that specifically

class Parent { str = 'a'; } class ParentExtended extends Parent { num = 1; } class MyClass { static property?: Parent static method (p: Parent): void {} static func?: (pParam: Parent) => void } const pe: ParentExtended = { str: &ap ...

Adding a unique key to every element within a JavaScript array

I am working with the array provided below which contains simple values. My goal is to add a key id before each value in the array, resulting in something like this: ["id:a", "id:b","id:c","id:d"]. Is there an easy way to achieve this? Any assistance would ...

Unable to access the newly created object's properties following the instantiation of a new resource in AngularJS

Currently, I am in the process of developing a new Resource utilizing AngularJS that falls under the category of Person. After successfully creating this resource, my goal is to retrieve the id associated with the new resource from the server. it('sh ...

`Angular Image Upload: A Comprehensive Guide`

I'm currently facing a challenge while attempting to upload an image using Angular to a Google storage bucket. Interestingly, everything works perfectly with Postman, but I've hit a roadblock with Angular Typescript. Does anyone have any suggesti ...

What is the process of uploading a video and showcasing it on an HTML page?

I have successfully uploaded images and displayed them on an HTML page. Now, I am looking to do the same for videos. Here is my current code: $('#addPhotosBtn').click(function() { $(this).parents().find('#addPhotosInput').click(); }) ...

Can one window interact with the window that opened it?

I am developing an application that requires users to log in using their Reddit account. Once they accept, a new window called SpawnedWindow opens, prompting users to connect with Reddit. Upon successfully connecting, SpawnedWindow redirects to a specific ...

What is the best way to insert a record into the rth column of the nth row in a table

In the table I'm working with, there are 6 columns and only 5 of them have data filled in. The last column is currently empty for all rows. I am now trying to populate the last column of each row with some data. Can someone guide me on how to use a f ...

What is the best way to retrieve a specific value in an array object using JavaScript?

I'm working with an array that has the structure shown below: balance = [ {id: 2, is_selected: true}, {id: 4, is_selected: true}, {id: 15, is_selected: false}, {id: 137, is_selected: false}, {id: 30, is_selected: false} ]; Is ther ...

What is the reason behind caching form data in an ajax call?

After the first successful submission, I am facing an issue where the original form data is being re-sent even when new values are submitted for a second attempt. How can I reset and reload the data to avoid this problem? I have tried several approaches i ...

The Nextjs application folder does not contain the getStaticPaths method

I encountered a problem with the latest nextjs app router when I tried to utilize SSG pages for my stapi blog, but kept receiving this error during the build process app/blog/[slug]/page.tsx Type error: Page "app/blog/[slug]/page.tsx" does not m ...

Continuously decrease a sequence of identical numbers in an array through recursion

One of the key challenges was to condense an array of numbers (with consecutive duplicates) by combining neighboring duplicates: const sumClones = (numbers) => { if (Array.isArray(numbers)) { return numbers.reduce((acc, elem, i, arr) => { if ( ...

Ajax: If a GET request is made, the page will automatically refresh

EcmaScript 6, jQuery 3.1.0 Fiddle: https://jsfiddle.net/Kifsif/k6gw1gnw/10/ Heroku: A plus sign can be found on the page which is supposed to add a form just above it when clicked. The issue arises when adding a form via AJAX as it ends up being displa ...

What causes the [$parse:syntax] error when I tap on the arrow icon within Google Maps?

.controller('MapCtrl', [ '$scope', '$http', '$location', '$window', function ($scope, $http, $location, $window) { $http.get('****').success(function (data, dealers, response) { ...

What is the best way to restrict the size of a table that is filled with data from a database?

Currently using a combination of React, Node, Express, and Postgres to populate a table with data retrieved from Postgres. The issue arises when the table becomes overly long, prompting the need to display only 5 rows at once while adding a scroll bar for ...

Troubleshooting: Issue with append function not functioning properly after click event in Angular

I am struggling to implement a basic tooltip in AngularJS. Below is the HTML I have: <span class="afterme" ng-mouseover="showToolTip('this is something', $event)" ng-mouseleave="hideToolTip();"> <i class="glyphicon glyphicon-exclama ...

Why doesn't the address bar automatically update to the correct path after successfully authenticating with NextAuth using credentials?

Is there a way to automatically refresh the URL path once a successful login is completed with credentials? I attempted to set up credential authentication similar to the guide provided by Next in their tutorial here. However, I am only using email for au ...

After updating the name of an input control for validation, the ASP.NET validators are no longer functioning properly

Adding "runat=server" to an input control allows for ASP.NET validators to be specified, but it can create complications when dynamically adding rows with JavaScript. Each input control must follow a specific naming convention, like "inputControl_" + count ...

Troubleshooting a problem with scrolling functionality while keeping the header in place and ensuring the correct tab is highlighted

I've successfully created a page with a fixed menu that appears when scrolling, and the tabs activate based on their corresponding section IDs. However, I'm encountering some issues: The scrolling behavior is not precise; when scrolling to sec ...