Maintaining the initial value of a textbox in jQuery across various focusin events

Struggling to accurately explain the process, so feel free to check out this helpful fiddle.

In my form, there are several text input fields and a single submit button. The submit button becomes enabled once any of the form fields have been altered. If a textbox's value is changed, it will receive a new yellow background color using addClass to indicate the modification. The original value is saved during the focusin event and then compared with the new value during onchange.

However, I would like to prevent the original old value from changing when I edit the textbox value and refocus, in order for the background-color to reset accordingly.

Appreciate your help!

Answer №1

To utilize the defaultValue property, follow this code snippet:

var adminWeb = window.adminWeb || {};

adminWeb.dirtyHandling = (function() {
  var createView = function() {
    $("form")
      .each(function() {
        $(this).data("serialized", $(this).serialize());
      }).on("change input", 'input:text', function(e) {
        $(this).toggleClass("textbox-changed", this.value !== this.defaultValue);

        var $form = $(this).closest('form');
        $form.find("input:submit, button:submit")
          .prop("disabled", $form.serialize() === $form.data("serialized"));
      })
      .find("input:submit, button:submit")
      .prop("disabled", true);
  };

  return {
    init: createView
  };

})();

$(function() {
  adminWeb.dirtyHandling.init();
});
.textbox-changed {
  background-color: rgba(255, 255, 0, 0.3)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="" action="" method="post">
  <input type="text" value="Carl" name="firstname" id="firstname" />
  <input type="text" value="Johnson" name="lastname" id="lasttname" />
  <br />
  <br />
  <br />
  <br />
  <br />
  <button id="submit-data" disabled="" type="submit">Save changes</button>
</form>


To ensure your code functions correctly, implement a data property to store the original value as shown below:

var adminWeb = window.adminWeb || {};

adminWeb.dirtyHandling = (function() {
  var createView = function() {
    $("form")
      .each(function() {
        $(this).data("serialized", $(this).serialize());
      }).on("focusin input:text", function(e) {
        var $t = $(e.target);
        var dvalue = $t.data('default-value');
        if (typeof dvalue == 'undefined') {
          $t.data('default-value', $t.val())
        }
      }).on("change input", function(e) {
        var txt = $(e.target);
        if (txt.is("input:text")) {
          txt.addClass("textbox-changed");
          if (txt.val() === txt.data('default-value')) { 
            // Compare with the original value
            txt.removeClass("textbox-changed");
          }
        }

        $(this)
          .find("input:submit, button:submit")
          .prop("disabled", $(this).serialize() === $(this).data("serialized"));
      })
      .find("input:submit, button:submit")
      .prop("disabled", true);
  };

  return {
    init: createView
  };

})();

$(function() {
  adminWeb.dirtyHandling.init();
});
.textbox-changed {
  background-color: rgba(255, 255, 0, 0.3)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="" action="" method="post">
  <input type="text" value="Carl" name="firstname" id="firstname" />
  <input type="text" value="Johnson" name="lastname" id="lasttname" />
  <br />
  <br />
  <br />
  <br />
  <br />
  <button id="submit-data" disabled="" type="submit">Save changes</button>
</form>

Answer №2

It seems like there might be some confusion in your question. Are you aiming for something similar to this?

To achieve the desired outcome, you should eliminate the class during the focusin event.

Answer №3

To determine whether or not to apply a specific class, use a data attribute to store the original value and compare it with the current value. Iterate through each element to check if any of them have been modified. Here is an example...

<input data-original="Alice" value='Alice' type='text' />
<input type='submit id='submit' />

var inputs$ = $('[data-original]');

$('[data-original]').change(function (e) {
    var modified = false;
    $.each(inputs$, function () {
        var el$ = $(this);
        if (el$.attr('data-original') != el$.val()) {
            el$.addClass('highlight');
            modified = true;
        }
    });

    if (modified) {
        $('#submit').removeAttr('disabled');
    }
    else {
        $('#submit').attr('disabled', 'disabled');
    }

});

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

I can't seem to retrieve any values from the API other than "chicken"

Is there a way to make the search bar in my recipe app look for recipes that I provide, rather than fetching data from useState? Any suggestions on how I can achieve this? import React, { useEffect, useState } from 'react'; import Recipe from &ap ...

Is it necessary for Webpack to package all dependent node modules with the final bundle in production mode?

It's common knowledge that when we run npm run build, React scripts utilize Webpack to create a bundle by examining the entire dependency graph (following imports) and generating a bundle.js which is then stored in the dist/build folder for production ...

Using unicode characters to style your Angular application

Hey there! I have an Angular 5 app on StackBlitz that implements table sorting. You can check it out here: https://stackblitz.com/edit/angular-rxdzom. The code for this app is based on the example from . In the app, I've used a stylesheet at ./app/sor ...

Display the flowplayer div when the anchor is clicked

I have a dynamic CGI page that displays a list of files. The number of files varies based on uploaded content, so I am looking to create previews for video files. Below is a snippet of HTML code: <TMPL_LOOP files> <tr> <td&g ...

Updating a div using Ajax within a Rails application

In my to-do app, each task has subtasks stored in div elements with p id="task_"+<%=task.id%>I have a form for creating a new subtask on every show page of my project. To understand better, here is the code I am using: This is the show.html.erb fil ...

Click on a specific image in a table using Cypress with a specific source URL

I need help with a query for Cypress regarding a table of items, each item having active (blue) and not active (black) images. How can I set up this query? Below is an image of the table list: https://i.stack.imgur.com/74qzb.png And here is the HTML code ...

Stop the Nav bar item from collapsing

Alright, let's talk about the scenario: The situation is that I have a basic, plain, nav nav-tabs navigation bar with a few elements and a rightmost item (with pull-right) positioned as an <li> element which includes a dropdown. As the window ...

Leveraging jQuery to interact with elements within an ASP:GridView

Currently, I am attempting to enhance the style of certain elements within a grid-view using jQuery. However, it seems that jQuery is not able to recognize those specific elements. Here's an example of what I've been trying to do: $("name").css( ...

Guide to creating seamless integration between AngularJS routing and ExpressJS routing when using html5mode

Yesterday, I posted a question on stackoverflow about my webpage's CSS and JavaScript not including after a refresh. I discovered that it was caused by html5mode, but I have been searching for a solution since then with no luck getting an answer. My ...

Utilizing GET parameters containing spaces

Is it possible to retrieve a variable that contains spaces? When I attempt to do so, only the first word is returned. I attempted to use the htmlspecialchars function, but it did not resolve the issue. In my code, within categories.php, I have the followi ...

React: Implementing localStorage token addition in loginHandler function using State hook is not functioning as expected

I've implemented an AuthContextProvider in my React application to handle user authentication and logout functionality: import React, { useState } from "react"; import axios from "axios"; import { api } from "../api"; co ...

Transforming a CSV document into a JSON format in order to generate a hierarchical tree structure for constructing a D3 categorical tree diagram

I have a CSV file that is structured like this: "","Sequence","Paths","sequence_length" "1","Social -> Social -> Social -> Social -> Social -> Social -> Social -> Social",29,8 "2","Social -> Social -> Social -> Social -> S ...

Problems revolving around the fundamental CSS drop-down menu concept

I'm struggling to center a CSS drop-down menu on my webpage without causing the drop-down effect to break. No matter what I try, it seems to mess up. What am I missing? Snippet of code: html,body,div,span,applet,object,iframe,h1,h2,h3,h4,h5,h6,p,b ...

Adjust the class attribute in real-time

My image doesn't appear in the correct position when I dynamically set it using the margin-top. Below is an image with a red arrow pointing to the right, which is what I want: https://i.stack.imgur.com/ue4mY.png The CSS I have is as follows: .file ...

It seems that Firefox is ignoring the word-wrap style when the class of a child element is changed

Take a look at this: var iconIndex = 0; var icons = ['check', 'chain-broken', 'flag-o', 'ban', 'bell-o']; $('button:eq(0)').click(function() { iconIndex = (iconIndex + 1) % icons ...

Angular 9: The instantiation of cyclic dependencies is not allowed

After transitioning from Angular 8 to Angular 9, I encountered an issue with a previously functioning HTTP communication service. The error message now reads: Error: Cannot instantiate cyclic dependency! HttpService at throwCyclicDependencyError (core ...

Retrieve the HTML code from a webpage on a different domain

Looking to extract HTML from another domain. Attempted solution: $.get("http://website1.com", function(data) { alert("Data Loaded: " + data); }); (not working) For example, as the owner of two websites: website1.com website2.com Now, the goal is to ret ...

Tips for displaying a combobox popover from @reach/combobox within a MUI dialog element

I've been attempting to integrate a map from the Google Maps API and a combobox popover from @reach/combobox within a MUI dialog component. However, I've encountered an issue where the combobox popover isn't displaying. After some investigat ...

AngularJS not compatible with Splice functionality

Currently, I am working on a form for an Items list that allows users to add, edit, and delete items. While the add and edit functionalities are working correctly, I am facing some issues with the delete functionality. Below is a snippet of my code that i ...

Incorporating a pre-loaded database into a jQuery Mobile Phonegap app

After developing a native iPhone app that utilized an SQLite database with thousands of rows, I am now facing the task of creating an Android app using Phonegap. While I have some knowledge in HTML, CSS, and JavaScript, I am fairly new to Phonegap and jQue ...