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 Twitter

Newsletter

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

Dev Digest 146: 🥱 React fatigue 📊 Query anything with SQL 🧠 AI News

Why it may not be needed to learn React, why Deepfake masks will be a big problem and your spirit animal in body fat! 

Dev Digest 147: Free Copilot! Panel: AI and devs! RTO is bad! Pi plays!

Free Copilot! Experts discuss what AI means for devs. Don't trust containers. Mandated RTO means brain drain. And Pi plays Pokemon!

Dev Digest 148: Behind the scenes of Dev Digest & end of the year reports.

In 50 editions of Dev Digest we gave you 2081 resources. Join us in looking back and learn about all the trends this year.

Dev Digest 149: Wordpress break, VW tracking leak, ChatGPT vs Google.

Slowly starting 2025 we look at ChatGPT vs Google, Copilot vs. Cursor and the state of AI crawlers to replace web search…

Dev Digest 150: Shifting manually to AI.

Manual coding is becoming less of a skill. How can we ensure the quality of generated code? Also, unpacking an APK can get you an AI model.

My other work: