Frank Frank - 1 year ago 82
Javascript Question

JavaScript -- clear form after values are submitted

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


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

Answer Source

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:

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

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download