41

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?

designersvsoft
  • 1,861
  • 9
  • 39
  • 66

13 Answers13

115
$("#cform")[0].reset();

or in plain javascript:

document.getElementById("cform").reset();
henryabra
  • 1,433
  • 1
  • 10
  • 15
  • @VisioN just for the record - the `each` would not throw an exception in case the id "cform" doesn't exist – henryabra May 17 '12 at 10:25
  • @henryabra True but it doesn't make sense for static form as in question. Otherwise, yes, it is a workaround to `if`. – VisioN May 17 '12 at 10:35
  • @henryabra could you please explain why "[0]", why does $(selector)[0].reset() work and not just $(selector).reset()? – alphapilgrim Dec 03 '15 at 02:40
  • 1
    @alphapilgrim the output of `$(selector)` is a DOM element result array which is also a jQuery monad. The `reset()` function is not part of the jQuery API (thus wont work on the jQuery monad). Since the talked element exist and has an id then the result array is guaranteed to have exactly one DOM element. The `[0]` operator retrieves it and since its an HTML form then is has the `reset()` function. – henryabra Jan 06 '16 at 16:53
14

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('');

            });
Prasenjit Kumar Nag
  • 13,391
  • 3
  • 45
  • 57
6

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

gdoron
  • 147,333
  • 58
  • 291
  • 367
3
$('.contactForm').submit(function(){
    var that = this;

    //...more form stuff...

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

        //...more success stuff...

        that.reset();
    });
});
Joseph
  • 117,725
  • 30
  • 181
  • 234
2

Simply

$('#cform')[0].reset();
Norse
  • 5,674
  • 16
  • 50
  • 86
2

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>
Hamid
  • 21
  • 5
1
$.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/

Ankur Verma
  • 5,793
  • 12
  • 57
  • 93
1

Set id in form when you submitting form

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

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

    </form>

   set in jquery 

   document.getElementById("cform").reset(); 
Siddharth Shukla
  • 1,063
  • 15
  • 14
1
$('#formid).reset();

or

document.getElementById('formid').reset();
RobC
  • 22,977
  • 20
  • 73
  • 80
iamnonso
  • 105
  • 1
  • 4
1

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();
}
Community
  • 1
  • 1
Dexter
  • 7,911
  • 4
  • 41
  • 40
1

just use form tag alone, like this :

  $.ajax({
    type: "POST",
    url: "/demo",
    data: dataString,
    success: function () {
      $("form")[0].reset();
      $("#test").html("<div id='message'></div>");
      $("#message")
        .html("<h2>Contact Form Submitted!</h2>")
        .append("<p>We will be in touch soon.</p>")
        .hide()
        .fadeIn(1500, function () {
          $("#message").append(
            "<img id='checkmark' src='images/check.png' />"
          );
        });
    }
  });
  e.preventDefault();
});
0

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

example from your script above:

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

iamnonso
  • 105
  • 1
  • 4
  • This is exactly what the accepted answer (and some of the other answers) already say. This answer adds nothing useful. – Lauren Yim Aug 29 '20 at 00:26
0

If you are using a form tag in your form. Then

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

This code will work perfectly but in case you are not using any form tag then you can try to set an empty value to each input field Like this.

$('input[type="text"],textarea').val('');
Sifat Kazi
  • 46
  • 3