views:

51

answers:

3

If I put a form control on the page with a value already set, triggering the containing form's reset functionality will return the value to the original value at the time when the page was loaded.

However, if I create a form control using javascript, and append it to the DOM, the form control will be erased and made blank when the form is reset. How can I prevent this behavior? I would like to give the input a default value, so it will be treated the same way as a control that was on the page at page load.

In the following example, clicking RESET clears one input (the script-added one), but not the other (the static one). What I want is for both inputs to retain their value.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"&gt;

<html xmlns="http://www.w3.org/1999/xhtml" xmlns:wicket="http://wicket.sourceforge.net/" xml:lang="en" lang="en">
    <head>
    </head>
    <body>
        <form id="container">
            <input type="reset" value="RESET" />
            <input type="text" value="DefaultValue" />
        </form>
        <script type="text/javascript">
        window.onload = function() {
            var input = document.createElement('input');
            input.setAttribute('value', 'DefaultValue2');
            document.getElementById('container').appendChild(input);
        };
        </script>
    </body>
</html>

Though I have not included jQuery in this simple test case, my project uses jQuery, and I would be happy for a jQuery solution.

A: 

Forms have an onreset event, which, according to ppk is available cross-browser. If the Javascript created element isn't reset to its initial value when the reset button is pressed, you could use the event to reset it "manually".

However, by my testing resetting a javascript created element (I'm using Prototype in my example but it shouldn't make a difference) works in Firefox 3.6 and Chrome 5 without needed an additional onreset handler (but not in IE6).

Daniel Vandersluis
A: 

You'll need to add more functionality to the default 'reset' input, for example you could use the onReset event to set input's value = 'defaultvalue2'. This would reset both input fields, one statically and the other via the onReset method.

Eton B.
+6  A: 

The form reset() uses the defaultValue property, so all you need to do is set that...

window.onload = function() { 
  var input = document.createElement('input');
  input.value = input.defaultValue = 'DefaultValue2';
  document.getElementById('container').appendChild(input); 
}; 
Josh Stodola
+1 Nice, I didn't know about `defaultValue`.
Daniel Vandersluis
Awesome! Thanks.
RMorrisey