Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I prevent a form reset from clearing my <input type="text"> element?

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">

<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.

like image 684
RMorrisey Avatar asked Aug 13 '10 15:08

RMorrisey


People also ask

How do you stop form from resetting on submit?

You can use preventDefault method of the event object. Show activity on this post. Show activity on this post. stopPropagation should have no effect.

How do I keep form data after submitting the form using javascript?

To keep the values, you must fill in the values on the server while rendering the page. Usually, you can simply copy the data from the HTML request parameters into the fields. Usually, you cannot simply copy the HTML request parameters into the fields.

How can we keep textbox value after submit in PHP?

You can just echo $_POST['name'] in the value attribute of the input. Make sure you check POST values to avoid XSS. I also put up the update DB function, as you don't need to show the form to the user if the name in longer the 4 chars!


1 Answers

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); 
}; 
like image 97
Josh Stodola Avatar answered Nov 15 '22 09:11

Josh Stodola