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.

[tags]netmagazine,JavaScript,formvalidation,webdevtrick[/tags]

Share on Mastodon (needs instance)

Share on BlueSky

Newsletter

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

Don't stop thinking, AI Slop vs. OSS Security, rolling your own S3 Despite AI you still need to think, Bitter lessons from building AI products,  AI Slop vs. OSS security and pointer pointer…
200: Building for the web, what's left after rm -rf & 🌊🐴 vs AI What remains after you do a rm -rf? Why do LLMs know about a seahorse emoji? What image formats should you use? How private is your car?
Word is Doomed, Flawed LLM benchmarks, hard sorting and CSS mistakes Spot LLM benchmark flaws, learn why sorting is hard, how to run Doom in Word and how to say "no" like a manager.
30 years of JS, Browser AI, how attackers use GenAI, whistling code Learn how to use AI in your browser and not on the cloud, why AI makes different mistakes than humans and go and whistle up some code!
197: Dunning-Kruger steroids, state of cloud security, puppies>beer

My other work: