【问题标题】:clear form values after submission ajax提交ajax后清除表单值
【发布时间】:2012-05-17 10:06:28
【问题描述】:

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

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

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

【问题讨论】:

标签: javascript jquery ajax


【解决方案1】:
$("#cform")[0].reset();

或者用纯javascript:

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

【讨论】:

  • @VisioN 仅作记录 - 如果 id "cform" 不存在,each 不会抛出异常
  • @henryabra 是的,但对于所讨论的静态形式没有意义。否则,是的,这是if 的解决方法。
  • @henryabra 你能解释一下为什么“[0]”,为什么 $(selector)[0].reset() 有效,而不仅仅是 $(selector).reset()?
  • @alphapilgrim $(selector) 的输出是一个 DOM 元素结果数组,它也是一个 jQuery monad。 reset() 函数不是 jQuery API 的一部分(因此不能在 jQuery monad 上工作)。由于被谈论的元素存在并且有一个 id,那么结果数组就保证只有一个 DOM 元素。 [0] 运算符检索它,因为它是一个 HTML 表单,所以它具有 reset() 函数。
【解决方案2】:

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

            });

【讨论】:

    【解决方案3】:

    使用这个:

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

    或者如果您使用this 引用该表单:

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

    :input === &lt;input&gt; + &lt;select&gt;s + &lt;textarea&gt;s

    【讨论】:

    • :input 将选择 type='submit' 并重置它的值,这是不可取的。
    • 也许:input:not(:submit) 更短。
    • @VisioN。我想了想,但它必须是:input:not(:submit):not(:button)...所以不值得。
    【解决方案4】:
    $('.contactForm').submit(function(){
        var that = this;
    
        //...more form stuff...
    
        $.post('mail.php',{...params...},function(data){
    
            //...more success stuff...
    
            that.reset();
        });
    });
    

    【讨论】:

      【解决方案5】:

      简单

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

      【讨论】:

        【解决方案6】:
        $.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/

        【讨论】:

          【解决方案7】:

          它起作用了:在 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>
          

          【讨论】:

            【解决方案8】:

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

                 <form action="" id="cform">
            
                   <input type="submit" name="">
            
                </form>
            
               set in jquery 
            
               document.getElementById("cform").reset(); 
            

            【讨论】:

              【解决方案9】:
              $('#formid).reset();
              

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

              【讨论】:

                【解决方案10】:

                香草!

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

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

                【讨论】:

                  【解决方案11】:

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

                  上面脚本中的示例:

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

                  【讨论】:

                  • 这正是公认的答案(以及其他一些答案)已经说过的。这个答案没有任何用处。
                  猜你喜欢
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 2018-09-30
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 2011-07-23
                  • 2011-10-21
                  相关资源
                  最近更新 更多