How to get old Value with onchange() event in text box
Ready for an immediate solution? For capturing a text box's original value upon modification, utilize the onfocus
event to remember the value, then use onchange
event to sense the new value. Here's a simple example:
In this snippet, onfocus
saves the textbox value in previousValue
each time it comes under focus. If the value changes, onchange
triggers, giving you both the new and the previous values.
Elaborative illustration
Below we dive much deeper into the ocean of capturing old and new values in text boxes:
On storing old values using custom properties and event handlers
HTML expando properties come as saviours to store and handle data specific to an element:
On utilizing HTML5 data attributes for enhanced value tracking
In the HTML5 era, data attributes have emerged as a neat, standard way to store bespoke data:
On using a JavaScript object to handle mass-surveillance of text boxes
Keeping track of multiple text boxes and their values is cumbersome manually, thank God we can automate it by architecting a JavaScript object to do this:
On digging up initial values using defaultValue property
In scenarios when you want to harvest the initial value of a text input devoid of any human interaction, rely on the stoic defaultValue
property:
Understanding complex scenarios
In real-world cases, working with forms containing multiple inputs, dynamic elements, or asynchronous operations can appear as a maze. Incorporate the proven methods mentioned above to track input changes consistently.
Special cases and considerations
Keep your eyes open for possible edge cases like dynamically added input elements to the DOM. Besides, mind the gap with browser compatibility and ensure your JavaScript code has the grace to degrade as per necessity.
Professional tips for optimized execution
For efficient performance and effective memory management, a handy trick is to use event delegation on a parent element. This couples a single event listener to control focus
and change
events for all inputs:
Now that's a surefire way to keep track of changing values with an eagle-eye precision.
Was this article helpful?