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

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.

4 Responses to “Q&A: How can I track the change in a form field before the form was submitted”

  1. David Joseph Says:

    It’s actually “.net” notice the dot :)

    Love the Spam capture by the way

  2. mde Says:

    The defaultValue is a nice trick, but only works for text, password, and file inputs. BTW, there’s a built-in method in the Fleegix.js JavaScript Toolkit for getting the changes in a form, fleegix.form.diff. I’d provide a link, but it looks like the spammers have spoiled it for the rest of us. :)

  3. richard ladson Says:

    Chris,
    I hate to comment on your faux console solution because I am a newbie at javascript, but I think there is a problem in the Mac/Safari environment.

    The “try it” URL (http://icant.co.uk/sandbox/fauxconsole/) works ok with Mac/Firefox but not with Mac/Safari. I simply entered the subject URL into each browser and faux console worked with Firefox but not with Safari.

    It may be just my ignorance, but if so, what am I doing wrong.

    Richard

  4. Chris Says:

    Richard, this is because Safari already has a console: Screenshot

Leave a Reply

Wait till I come! is the blog of Christian Heilmann , a developer evangelist living and working in London, England. Download vcard.

Feed me, Seymour: Entries (RSS) and Comments (RSS).