提交ajax后清除表单值

时间:2012-05-17 10:06:28

标签: javascript jquery ajax

我使用以下脚本来验证我的联系表单。

//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;


        } 
  });

这是我的表格

<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>

我需要在成功提交后清除表单字段值。我怎么能这样做?

11 个答案:

答案 0 :(得分:83)

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

或简单的javascript:

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

答案 1 :(得分:11)

您可以在$ .post调用成功回调中执行此操作

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

            });

答案 2 :(得分:2)

使用它:

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

或者如果您对this的表单有提及:

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

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

答案 3 :(得分:2)

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

    //...more form stuff...

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

        //...more success stuff...

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

答案 4 :(得分:1)

简单地

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

答案 5 :(得分:0)

$.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/

答案 6 :(得分:0)

它的工作原理:在ajax成功后调用此函数并将表单ID作为参数发送。像这样的东西:

此功能清除所有输入字段值,包括按钮,提交,重置,隐藏字段

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

*此功能清除除按钮,提交,重置,隐藏字段之外的所有输入字段值  * * /

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

示例:

<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>

答案 7 :(得分:0)

提交表单时在表单中设置ID

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

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

    </form>

   set in jquery 

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

答案 8 :(得分:0)

$('#formid).reset();

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

答案 9 :(得分:0)

香草!

我知道这篇文章很老了。
由于OP使用的是jquery ajax,因此将需要此代码。
但是对于那些寻找香草的人。

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

答案 10 :(得分:0)

使用ajax reset()方法,您可以在提交后清除表单

上面脚本中的示例:

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