Re: How to check that a form has been changed
Available news archives: comp.lang.tcl - comp.lang.python - comp.security.firewalls - sci.crypt - comp.lang.php - comp.lang.javascript
Google
 
Web news.hping.org


comp.lang.javascript archive

Re: How to check that a form has been changed

From: RobG <rgqld@iinet.net.au>
Date: Sun Apr 30 2006 - 14:09:56 CEST

Taras_96 wrote:
> Hi everyone,
>
> How do you detect that a form element has been changed?

It depends on what you mean by 'changed'. Do you mean if any control
has a value that differs from its default value? Or does 'changed'
include where a user changes to some other value, then back to the default?

> This thread:
>
> http://groups.google.com/group/comp.lang.javascript/browse_thread/thread/9ae1c9d419264380/125a82c9be127790?lnk=st&q=checking+html+form++(updated+OR+edited+OR+changed)&rnum=28&hl=en#125a82c9be127790
>
> suggests that you attach onChange event handlers to every form element,
> and when the handler fires you update a global 'isChanged' variable.

An alternative is to go through all the form controls and test if their
current value is the same as their default value. Where it isn't,
they've been changed.

How you do the test depends on the type of element. Inputs of type
"text", "file" or "password" have a defaultValue attribute that is their
default value, so you can test their current value against that.

For select elements, test if the selected option's 'defaultSelected'
attribute is 'true'. For radio buttons and checkboxes, test their
'defaultChecked' attribute.

Another scheme is to always have the first control of any group selected
(select, radios), no checkboxes selected and no value in text controls.
  Then you can test against logic rather than values.

Another option is to use onload to create an object that stores the
names or ids of form controls and their values, then you can check
against that when the form is submitted.

> This technique seems to be a bit messy to me (I have many form
> elements), I was thinking about storing the original form object in a
> javascript variable when the body loads (in the bodie's onLoad event
> handler),

How to you expect to achieve that?

> and upons submission, doing a javascript equality comparison
> with the current form object. If nothing has changed, then the two
> objects should be equal, right?

In JavaScript, objects are only equal to themselves (I wish I had a
reference for that statement but I don't). There is no way to copy an
objectA to create a new objectB so that :

    objectA == objectB

returns true; it will always return false. The statement will only be
true if objectA and objectB are references to the same object.

> if(oldObject == document.getElementById('form'))
> {
> alert('has changed!');
> }
>
> Would this work?

No - that is, it will not reliably test whether the form has been
changed or not.

-- 
Rob
Received on Mon May 1 05:27:52 2006