Reset and clear the HTML form after submitting – when you hit browser’s back button

This is a small issue but sometimes important. Well this is not a major post by me nor a major find, but I did run into some trouble while trying this particular thing out. Hence thought of recording it somewhere, so that I do not have to re-invent the wheel again. Here is the use case – there is an HTML form which is to be filled up and submitted to a server side script (let’s say some PHP code). After successful submission the user hits the back button of the browser. All the form fields and values should be reset and set to its initial configuration.

I tried several different techniques and implementations but ran into some or the other problems mainly because of browsers – different browsers behaving differently. On some browsers something works while on the others it does not. Thanks to these differences in spite of a universal and a common W3C standard. But I finally found a rather easy solution and cached onto it. This post will talk on that particular method with an example.

So the clue is very simple – reset the form after it is submitted so that when the user hits the back button every field in the form is initialized and reset (no previous values are left behind). How?? Let’s see in this example,

First I have a simple HTML form with a checkbox, two input fields and a button,

<body>
  <form method="get" name="myForm" action="submit.php">
    Salaried: <input type="checkbox" name="salaried"/>
    <br/>
    First Name: <input type="text" name="input1"/>
    <br/>
    Last Name: <input type="text" name="input2"/>
    <br/>
    <input type="button" value="Submit" onclick="submitForm()"/>
  </form>
  <script type="text/javascript" src="form_submit_script.js"></script>
</body>

Note that the button is not a submit button, but a normal push button. I have a onclick event handler attribute assigned to it which calls a function submitForm() when user clicks on it. Inside this function I do a small validation and then finally submit the form. The trick to remove the previous values when you hit the back button in the browser is inside this function. Let’s check it out,

function testSubmit()
{
  var x = document.forms["myForm"]["input1"];
  var y = document.forms["myForm"]["input2"];
  if(x.value =="" || y.value=="")
  {
    alert('Not allowed!!');
    return false;
  }
  return true;
}
function submitForm()
{
  if(testSubmit())
  {
    document.forms["myForm"].submit(); //first submit
    document.forms["myForm"].reset(); //and then reset the form values
  }
}

You can see the submitForm(){} function definition in the code block above. First I do a form validation for empty fields, which is very simple and I will not go inside it. After successful validation the form is submitted using the standard submit() method and then I reset the form using the standard form reset() method. This ensures that every form field is reset and there are no values left behind in the text boxes. You van verify this by first checking the checkbox, putting some values in the text boxes and clicking on the button. This will take you tot he submit php page (The PHP page is not in my server, so you get a 404 error). Then click the back button of your browser and see that the checkbox and text inputs are reset. Try the same with the last line in the script commented as shown below,

//document.forms["myForm"].reset();

You will notice previous values being left behind. So, a very simple way to tackle this, but an effective one.

And this way of resetting works on all major browsers.

21 thoughts on “Reset and clear the HTML form after submitting – when you hit browser’s back button

      • I discovered that even though the reset code works to reset the form it has the unintended result of preventing the field required messages to work. Normally a user will be prompted to complete empty compulsory fields before submitting the form, but after adding the reset function, you simply get a cgi error message if there are any empty fields, i.e. it skips the step of prompting you to complete the form.

      • Erna,
        Thanks for pointing this out. I did not try the use case that you mentioned here. So might have missed out on it. I will try to update my post though.
        Joseph

  1. I think the admin of this site is truly working hard
    in favor of his web page, for the reason that here
    every stuff is quality based information.

  2. Well, it works fine, but I think that it’s much better solution is a creating a function like this

    function FormReset(){
    document.getElementById(‘ClearIt’).value=”;
    document.getElementById(‘ClearIt2’).value=”;
    document.getElementById(‘ClearIt3’).value=”;
    }

    And just…
    Or course in form we need to add id=”ClearIt” for each element…
    Sorry because my bad English…

  3. Actually, I don’t know if you code PHP yourself, but if you want to clear the form, you should really use php to clear the POST array. Like so: $_POST = array(); . That is only possible if you code the php that submits the form yourself. Otherwise you should really use the other method.

  4. I have a similar problem regarding resetting the values. Actually, I have a text file on my server and I want that the input data fetched from the user may stay there for sometime, say 10 seconds and after that it has to be reverted back to the original value. I am unable to get any idea of how to achieve it. Could you please help! Thanx in advance.

      • Hi Joseph,

        I actually want to control a remote camera on my phone to capture photos according to the desire of the user. So, to pass on the instructions from user on my webpage to android I need to store the command for capturing photo for sometime, say 10 seconds in form of a bit (1) on a file on my web server. I want this 1 to revert back to (0) automatically at the end of 10 seconds so that the phone may not get continous instruction of capturing the photos. So, problem is regarding this automatic reverting back. Please help me & Thanx for showing interest.

        Hitarth

  5. Hi joseph,
    I am a newbie please help me I have some problems. I have 2 forms, what I want is when user submit the first form he will be redirected to the 2nd form and will not be able to come back to the first form and see the data that he/she inserted. I have form1.php with form action=process.php. where process.php file is where I insert user answers into database and I used header(Location:form2.php) at the end of this file to redirect user to the 2nd form after submitting the first one. I dont know where I have to write your submitForm function.. also I added onclick=… and changed input type to “button” instead of “submit” but nothing happened. plase help me.. I really need it ..

    • I would suggest you to go with the Single Page Application architecture. So, when form 1 is submitted replace its HTML with form 2. This way the user would not be able to come back to form 1.

  6. I got around this a different way, being:

    jQuery:

    $(window).on(“unload”, function () {
    document.getElementById(“form ID”).reset();
    }

    Pure Javascript:

    window.onunload = function() { document.getElementById(“form ID”).reset(); }

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s