Javascript 提交ajax后清除表单值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10633605/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 02:14:23  来源:igfitidea点击:

clear form values after submission ajax

javascriptjqueryajax

提问by designersvsoft

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?

提交成功后,我需要清除表单字段值。我怎样才能做到这一点?

回答by henryabra

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

or in plain javascript:

或在普通的 javascript 中:

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

回答by Prasenjit Kumar Nag

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

您可以像这样在 $.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('');

            });

回答by gdoron is supporting Monica

use this:

用这个:

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

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

或者如果您有对表单的引用this

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


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

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

回答by Joseph

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

    //...more form stuff...

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

        //...more success stuff...

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

回答by Norse

Simply

简单地

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

回答by Ankur Verma

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

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

回答by Hamid

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

它有效:在ajax成功后调用此函数并发送您的表单ID,因为它是参数。像这样:

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>

回答by Siddharth Shukla

Set id in form when you submitting form

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

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

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

    </form>

   set in jquery 

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

回答by Emmanuel Nwaduba

$('#formid).reset();

or

或者

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

回答by Dexter

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.

我知道这个帖子很老了。
由于 OP 使用 jquery ajax,因此将需要此代码。
但对于那些寻找香草的人来说。

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