Explain Codes LogoExplain Codes Logo

How to get old Value with onchange() event in text box

javascript
event-handling
input-elements
javascript-objects
Nikita BarsukovbyNikita Barsukov·Dec 13, 2024
TLDR

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:

<input type="text" onfocus="this.previousValue = this.value" onchange="console.log('Super Old:', this.previousValue, 'Super New:', this.value);">

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:

<input type="text" onfocus="this.setAttribute('oldValue', this.value);" onchange="handleChange(this);">
function handleChange(element) { let oldValue = element.getAttribute('oldValue'); //no amnesia here let newValue = element.value; // fresher than morning coffee console.log('Super Old:', oldValue, 'Super New:', newValue); }

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:

let inputElements = document.querySelectorAll('input[type=text]'); inputElements.forEach(function(input) { input.onfocus = function() { this.dataset.previousValue = this.value; // like a vault for old values }; input.onchange = function() { alert('Super Old: ' + this.dataset.previousValue + ', Super New: ' + this.value); // and the vault opens }; });

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:

let valueMaster = {}; // the overseer function setupMaster(elementId) { let inputElement = document.getElementById(elementId); inputElement.onfocus = function() { valueMaster[this.id] = { old: this.value }; // the overseer takes notes }; inputElement.onchange = function() { valueMaster[this.id].recent = this.value; // the overseer updates notes alert('Super Old: ' + valueMaster[this.id].old + ', Super New: ' + this.value); }; }

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:

let inputElement = document.getElementById('myInput'); console.log('The initial value is:', inputElement.defaultValue); // like a time traveler going back to the beginning

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:

let formElement = document.querySelector('form'); formElement.addEventListener('focus', (event) => { if(event.target.tagName === 'INPUT') { event.target.dataset.previousValue = event.target.value; // Save old value in the vault } }, true); // Capture focus events in the capturing phase formElement.addEventListener('change', (event) => { if(event.target.tagName === 'INPUT') { alert('Super Old: ' + event.target.dataset.previousValue + ', Super New: ' + event.target.value); // Open the vault on change } });

Now that's a surefire way to keep track of changing values with an eagle-eye precision.