user636859
user636859

Reputation:

JavaScript -- clear form after values are submitted

I am using the following JavaScript code to clear a form on my page.

document.getElementById("bulletinForm").reset();

This code does indeed clear my form, but it does it before the information is sent to the server. I've tried calling as the onSubmit event on the form and as the onClick event on the Submit button. How do I send the information to the server before clearing the form? I am not currently using any Ajax with this. All I have is a Spring form that looks like this.

<form:form commandName="bulletin" method="post" action="processBulletin">
    <table>
        <tr>
            <td>Name: <font style="font-weight: bold; color: red;">
            <c:out value='${nameRequired}' /></font><br /></td>
        </tr>
        <tr>
            <td><form:input path="name" id="name" maxlength="100" value="" /></td>
        </tr>
        <tr>
            <td>Subject: <font style="font-weight: bold; color: red;">
            <c:out value='${subjectRequired}' /></font><br /></td>
        </tr>
        <tr>
            <td><form:input path="subject" id="subject" maxlength="1000" value="" /></td>
        </tr>
        <tr>
            <td valign="top">Message: <font style="font-weight: bold; color: red;">
            <c:out value='${messageRequired}' /></font><br /></td>
        </tr>
        <tr>                            
            <td><form:textarea path="note" id="note" cols="80" rows="100" value="" /></td>
        </tr>
        <tr>
            <td><input type="submit" value="Submit bulletin" onClick="clearForm()"/></td>
        </tr>
    </table>
</form:form>

Upvotes: 0

Views: 3880

Answers (2)

Guillermo
Guillermo

Reputation: 791

If you clear the form before submitting you won't get any data. That's also what should be expected. However you can circumvent this by sending the form without refreshing the site with an asynchroneous request. After sending the form data you can reset the form. A fast way would be doing it with the Javascript Framework jQuery:

$.ajax({
  type: 'POST',
  url: "url.html",
  data: $('#myForm').serialize(),
  success: function() {
    // This function is called after
    // sending the request successfully
    $('#myForm').trigger("reset");
  }
});

Sending AJAX request with pure Javascript is a bit more complicated.

Upvotes: 3

RattyLaa
RattyLaa

Reputation: 323

You could try manually submitting your form in Javascript, change the input type from submit to button and then you could have something like:

function onSubmit() {
  document.getElementById("bulletinForm").submit();
  document.getElementById("bulletinForm").reset();
  return false; //stop page refresh
}

Source: Clearing my form inputs after submission

Upvotes: 0

Related Questions