[javascript] clear form values after submission ajax

I am using the following script for validate my contact form.

//submission scripts
  $('.contactForm').submit( function(){
        //statements to validate the form   
        var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
        var email = document.getElementById('e-mail');
        if (!filter.test(email.value)) {
            $('.email-missing').show();
        } else {$('.email-missing').hide();}
        if (document.cform.name.value == "") {
            $('.name-missing').show();
        } else {$('.name-missing').hide();} 

        if (document.cform.phone.value == "") {
            $('.phone-missing').show();
        } 
        else if(isNaN(document.cform.phone.value)){
        $('.phone-missing').show();
        }
        else {$('.phone-missing').hide();}  

        if (document.cform.message.value == "") {
            $('.message-missing').show();
        } else {$('.message-missing').hide();}  

        if ((document.cform.name.value == "") || (!filter.test(email.value)) || (document.cform.message.value == "") || isNaN(document.cform.phone.value)){
            return false;
        } 

        if ((document.cform.name.value != "") && (filter.test(email.value)) && (document.cform.message.value != "")) {
            //hide the form
            //$('.contactForm').hide();

            //show the loading bar
            $('.loader').append($('.bar'));
            $('.bar').css({display:'block'});

        /*document.cform.name.value = '';
        document.cform.e-mail.value = '';
        document.cform.phone.value = '';
        document.cform.message.value = '';*/

            //send the ajax request
            $.post('mail.php',{name:$('#name').val(),
                              email:$('#e-mail').val(),
                              phone:$('#phone').val(),
                              message:$('#message').val()},

            //return the data
            function(data){

              //hide the graphic
              $('.bar').css({display:'none'});
              $('.loader').append(data);

            });

            //waits 2000, then closes the form and fades out
            //setTimeout('$("#backgroundPopup").fadeOut("slow"); $("#contactForm").slideUp("slow")', 2000);

            //stay on the page
            return false;


        } 
  });

This is my form

<form action="mail.php" class="contactForm" id="cform" name="cform" method="post">
  <input id="name" type="text" value="" name="name" />
  <br />
  <span class="name-missing">Please enter your name</span>
  <input id="e-mail" type="text" value="" name="email" />
  <br />
  <span class="email-missing">Please enter a valid e-mail</span>
  <input id="phone" type="text" value="" name="phone" />
  <br />
  <span class="phone-missing">Please enter a valid phone number</span>
  <textarea id="message" rows="" cols="" name="message"></textarea>
  <br />
  <span class="message-missing">Please enter message</span>
  <input class="submit" type="submit" name="submit" value="Submit Form" />
</form>

I need to clear the form field values after submitting successfully. How can i do this?

This question is related to javascript jquery ajax

The answer is


$('.contactForm').submit(function(){
    var that = this;

    //...more form stuff...

    $.post('mail.php',{...params...},function(data){

        //...more success stuff...

        that.reset();
    });
});

Set id in form when you submitting form

     <form action="" id="cform">

       <input type="submit" name="">

    </form>

   set in jquery 

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

Simply

$('#cform')[0].reset();

use this:

$('form.contactForm input[type="text"],texatrea, select').val('');

or if you have a reference to the form with this:

$('input[type="text"],texatrea, select', this).val('');

:input === <input> + <select>s + <textarea>s


$('#formid).reset();

or

document.getElementById('formid').reset();

it works: call this function after ajax success and send your form id as it's paramete. something like this:

This function clear all input fields value including button, submit, reset, hidden fields

function resetForm(formid) {
 $('#' + formid + ' :input').each(function(){  
  $(this).val('').attr('checked',false).attr('selected',false);
 });
}

* This function clears all input fields value except button, submit, reset, hidden fields * */

 function resetForm(formid) {
   $(':input','#'+formid) .not(':button, :submit, :reset, :hidden') .val('')
  .removeAttr('checked') .removeAttr('selected');
  }

example:

<script>
   (function($){
       function processForm( e ){
           $.ajax({
               url: 'insert.php',
               dataType: 'text',
               type: 'post',
               contentType: 'application/x-www-form-urlencoded',
               data: $(this).serialize(),
               success: function( data, textStatus, jQxhr ){
                $('#alertt').fadeIn(2000);
                $('#alertt').html( data );
                $('#alertt').fadeOut(3000);
               resetForm('userInf');
            },
            error: function( jqXhr, textStatus, errorThrown ){
                console.log( errorThrown );
            }
        });

        e.preventDefault();
    }

    $('#userInf').submit( processForm );
})(jQuery);

 function resetForm(formid) {
$(':input','#'+formid) .not(':button, :submit, :reset, :hidden') .val('')
  .removeAttr('checked') .removeAttr('selected');
 }
  </script>

Vanilla!

I know this post is quite old.
Since OP is using jquery ajax this code will be needed.
But for the ones looking for vanilla.

    ...
    // Send the value
    xhttp.send(params);
    // Clear the input after submission
    document.getElementById('cform').reset();
}

You can do this inside your $.post calls success callback like this

$.post('mail.php',{name:$('#name').val(),
                              email:$('#e-mail').val(),
                              phone:$('#phone').val(),
                              message:$('#message').val()},

            //return the data
            function(data){

              //hide the graphic
              $('.bar').css({display:'none'});
              $('.loader').append(data);

              //clear fields
              $('input[type="text"],textarea').val('');

            });

Using ajax reset() method you can clear the form after submit

example from your script above:

const form = document.getElementById(cform).reset();


$.post('mail.php',{name:$('#name').val(),
                          email:$('#e-mail').val(),
                          phone:$('#phone').val(),
                          message:$('#message').val()},

        //return the data
        function(data){
           if(data==<when do you want to clear the form>){

           $('#<form Id>').find(':input').each(function() {
                 switch(this.type) {
                      case 'password':
                      case 'select-multiple':
                      case 'select-one':
                      case 'text':
                      case 'textarea':
                          $(this).val('');
                          break;
                      case 'checkbox':
                      case 'radio':
                          this.checked = false;
                  }
              });
           }      
   });

http://www.electrictoolbox.com/jquery-clear-form/


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to ajax

Getting all files in directory with ajax Cross-Origin Read Blocking (CORB) Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource Fetch API request timeout? How do I post form data with fetch api? Ajax LARAVEL 419 POST error Laravel 5.5 ajax call 419 (unknown status) How to allow CORS in react.js? Angular 2: How to access an HTTP response body? How to post a file from a form with Axios