Reset /Delete input field value after sending with Ajax

Topics related to client-side programming language.
Post questions and answers about JavaScript, Ajax, or jQuery codes and scripts.
PloMar
Posts:48

Reset /Delete input field value after sending with Ajax

Hello,
I have the following code that sends form data with Ajax to a php script. It works, but after the form data is sent, the value added in the input field remains.

Code: Select all

<form action="/page.php" method="post" id="form">
  <input type="text" name="phone" required="required" />
  <input type="submit" name="sbmt" value="Send" />
</form>
<script>
$(document).ready(function(){
  $('#form').submit(function(e) {
    e.preventDefault();  // STOP default action
    e.unbind();  // to stop multiple form submit
    var form_data = $(this).serialize();  // get form data into a string with pairs: name=value
    $.ajax({
      type: 'POST',
      url: '/page.php',    
      data: form_data,
      success: function() {
        alert('Message sent');
      }
    });
  });
});
</script>
How can I reset (or delete) the value of the input field after the form data have been sent with Ajax?

Admin Posts:805
Hello,
You can use the following JavaScript code (in the "success" section of your Ajax function) when the data have already been sent, to delete individually the value of each form field.

Code: Select all

document.getElementById('id_form')['input_name'].value = ''; 
- "input_name" is the name of the input field added to its "name" attribute.

Or, the reset() function to reset the values of all elements in a form (same as clicking the Reset button).

Code: Select all

document.getElementById('id_form').reset();
In your code:

Code: Select all

success: function() {
  alert('Message sent');
  document.getElementById('form').reset();
}

Similar Topics