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:

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
196: AI killed devops, what now? LLM Political bias & AI security Learn how AI killed DevOps, create long tasks in JS, why 1 in 5 security breaches are AI generated code & play "The Scope Creep"
195: End of likes, JS Zoo and Tim Berners-Lee doesn't see AI vs Web Meta kills like buttons, Tim-Berners-Lee thinks AI won't kill the web, GitHub is ending toasts and the worst selling Microsoft product.

My other work: