Christian Heilmann

Q&A: How can I track the change in a form field before the form was submitted

Monday, February 12th, 2007 at 11:33 am

Q: I need to know when a user has changed the content of a form field before submitting the form. It’d be easy in PHP to compare the value stored in the DB with the $_POST value of the field, but this needs to happen in JavaScript.

A: There are several ways to do that. You could loop through all the fields when the document has loaded and store their values in an array and loop through and compare with that one when you submit the form (catching this via a submit handler on the form element and not when a button was clicked as the user might hit the enter to submit the form). However, this means you need to loop twice and when you run the loop to read out the values when the document has loaded the user might already have started editing the field. A much cleverer version is to run only one loop when the form was submitted and compare each field’s defaultValue property with the value property. It is not that known, but every field has a defaultValue property that stores what has been the value in the value attribute when the element was rendered. The value property stores what was entered in the field at the time you read it out. When the two don’t match, the user has altered the field.

This has been published in the Q&A session of the UK based paper magazine “net”. Reproduction rights were given by the publisher.

Share on Mastodon (needs instance)

Share on BlueSky

Newsletter

Check out the Dev Digest Newsletter I write every week for WeAreDevelopers. Latest issues:

160: Graphs and RAGs explained and VS Code extension hacks Graphs and RAG explained, how AI is reshaping UI and work, how to efficiently use Cursor, VS Code extensions security issues.
159: AI pipelines, 10x faster TypeScript, How to interview How to use LLMs to help you write code and how much electricity does that use? Is your API secure? 10x faster TypeScript thanks to Go!
158: 🕹️ Super Mario AI 🔑 API keys in LLMs 🤙🏾 Vibe Coding Why is AI playing Super Mario? How is hallucinating the least of our worries and what are rules for developing Safety Critical Code?
157: CUDA in Python, Gemini Code Assist and back-dooring LLMs We met with a CUDA expert from NVIDIA about the future of hardware, we look at how AI fails and how to play pong on 140 browser tabs.
156: Enterprise dead, all about Bluesky and React moves on! Learn about Bluesky as a platform, how to build a React App and how to speed up SQL. And play an impossible game in the browser.

My other work: