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

Best practices for using parent and child methods in Vue applications

I'm exploring the most effective approach to creating a modal component that incorporates hide and show methods accessible from both the parent and the component itself. One option is to store the status on the child. Utilize ref on the child compo ...

Efficiently updating database records without the need for page reloads using EJS

I'm working on a project that resembles the comment section on Reddit. Users can leave comments and others can reply to those comments. My tech stack includes Node, Express, MySQL, and EJS. The issue I'm facing is implementing the upvote/downvo ...

Traversing through pair of arrays simultaneously using forEach loop in JavaScript

I am trying to create a for loop that simultaneously iterates through two variables. One is an array named n, and the other, j, ranges from 0 to 16. var n = [1,2,3,5,7,8,9,11,12,13,14,16,17,18,20,21,22]; var m = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]; ...

Automatically populate input field values into a textarea using a separator with jQuery

There are multiple input fields to fill out: <input type="text" placeholder="name"> <input type="text" placeholder="age"> <input type="text" placeholder="gender"> <input type="text" placeholder="interest"> As I enter information i ...

"Experience the latest version of DreamFactory - 2.0.4

I'm encountering a 404 error when I send a request to my new DSP. GET http://example.com/api/v2/sericename/_table/tablename 404 (Not Found) Upon checking the Apache error.log, I found this message: ... Got error: PHP message: REST Exception #404 &g ...

Utilize ng-bootstrap in an Angular CLI project by integrating it with npm commands

I've been attempting to set up a project using Angular CLI with ng-bootstrap, but I'm having trouble getting the style to work properly. Here are the exact steps I followed (as outlined in the get-started page): Create a new project using `ng n ...

Step-by-step guide on how to make a POST request with session data to a specific endpoint in a Node.js server

Currently, I am utilizing express and have a task to execute a POST request to an internal endpoint in the server. Below is the code snippet I am using: request({ url : 'http://localhost:3000/api/oauth2/authorize', qs:{ transaction_id:re ...

CSS or jQuery: Which is Better for Hiding/Showing a Div Within Another Div?

Show only class-A at the top of the page while hiding all other classes (x,x,c). Hide only class-A while showing all other classes (x,x,c). Is it possible to achieve this? <div class="x"> <div class="y"> <div class="z"&g ...

Guide on displaying ajax data using PHP

I'm attempting to display the user-entered data by using AJAX to transfer it and then trying to print or echo it with PHP, but I'm having trouble getting it to work. enter code here Here is my code: <html> <head> <title> ...

Trouble with radio button selection in Pyppeteer, puppeteer, and Angular JS

I am struggling to select the 'fire' option in a radio button within a div element using Pyppeteer. Despite multiple attempts, I have not been successful. Here is the structure of the div with the radio button: <div _ngcontent-xqm-c396=" ...

Creating a continuous loop animation with CSS hover state

This piece of code creates an interesting effect when the text is hovered over. The slight shakiness adds a cool touch to it. However, this effect only occurs when the mouse is moved slowly; if the mouse remains stationary, the hover style takes precedence ...

Using jQuery to apply CSS styles to specific tags

I am attempting to retrieve the href of a pair of links and, based on the href value, I aim to apply specific CSS styles to that particular link. Below is the code I have used: $('.pane-menu-block-2 .menu li a').each(function(){ if($('a[hre ...

Can VueJS 1 and 2 be integrated within the same package.json configuration?

At the moment, my JavaScript files are using VueJS 1. However, I am preparing to work on a new section of the system and want to switch to VueJS 2. ...

Analyzing the current time against a user-inputted time using Javascript

Looking at this html and javascript code, the goal is to compare an input time with the current time. If the input time is less than 2 hours, "Less time" should be displayed in the label; if it's more than 2 hours, then "sufficient time" should appear ...

Combining two states in the Vuex store

In my Vuex store, I have two states: notes (synced notes with the server/DB) localNotes (unsynced notes that will move to 'notes' state upon syncing) To display the notes in a list, I use a getter that merges the two objects and returns the me ...

Using jQuery to combine the values of text inputs and checkboxes into a single array or string

I need to combine three different types of items into a single comma-separated string or array, which I plan to use later in a URL. Is there a way to merge these three types of data together into one string or array? An existing POST string User input f ...

Leveraging ES6 Symbols in Typescript applications

Attempting to execute the following simple line of code: let INJECTION_KEY = Symbol.for('injection') However, I consistently encounter the error: Cannot find name 'Symbol'. Since I am new to TypeScript, I am unsure if there is somet ...

"Flashes of canvas in constant motion between animated scenes

I have a practical exercise to do for school, but I am very new to HTML/JS. The issue I am facing is that my canvas is flashing, like it erases one image and then quickly displays another. I want both images to be displayed at the same time. Here is the co ...

Is there a way to verify if the password entered by the user matches the input provided in the old password field?

I am trying to compare the user's password with the one entered in the "oldPassword" input field. The challenge is hashing the input from the "oldPassword" field for comparison. How can I achieve this? Please review my ejs file and suggest improvement ...

I need three buttons, but I only want one to be active at a time. When one button is clicked and becomes active

function toggleSlideBox(x) { $("#"+x).slideToggle(300); } I am utilizing a JavaScript feature on buttons to create dropdowns that display forms, text, etc. When one button is clicked, it drops down along with the other two buttons, and when the ...