Clear form fields with jQuery

前端 未结 30 2712
甜味超标
甜味超标 2020-11-22 15:48

I want to clear all input and textarea fields in a form. It works like the following when using an input button with the reset class:

$(\".reset         


        
相关标签:
30条回答
  • 2020-11-22 16:24

    None of the above works on a simple case when the page includes a call to web user control that involves IHttpHandler request processing (captcha). After sending the requsrt (for image processing) the code below does not clear the fields on the form (before sending the HttpHandler request ) everythings works correctly.

    <input type="reset"  value="ClearAllFields" onclick="ClearContact()" />
    
     <script type="text/javascript">
           function ClearContact() {
               ("form :text").val("");
           }
        </script>
    
    0 讨论(0)
  • 2020-11-22 16:28

    Any reason this shouldn't be used?

    $("#form").trigger('reset');
    
    0 讨论(0)
  • 2020-11-22 16:28

    the code I see here and on related SO questions seems incomplete.

    Resetting a form means setting the original values from the HTML, so I put this together for a little project I was doing based on the above code:

                $(':input', this)
                    .not(':button, :submit, :reset, :hidden')
                    .each(function(i,e) {
                        $(e).val($(e).attr('value') || '')
                            .prop('checked',  false)
                            .prop('selected', false)
                    })
    
                $('option[selected]', this).prop('selected', true)
                $('input[checked]',   this).prop('checked',  true)
                $('textarea',         this).each(function(i,e) { $(e).val($(e).html()) })
    

    Please let me know if I'm missing anything or anything can be improved.

    0 讨论(0)
  • 2020-11-22 16:31

    I use this :

    $(".reset").click(function() {
      $('input[type=text]').each(function(){
         $(this).val('');
      });
    });
    

    And here is my button:

    <a href="#" class="reset">
      <i class="fa fa-close"></i>
         Reset
    </a>
    
    0 讨论(0)
  • 2020-11-22 16:32
    $(".reset").click(function() {
        $(this).closest('form').find("input[type=text], textarea").val("");
    });
    
    0 讨论(0)
  • 2020-11-22 16:33

    If i want to clear all the fields except accountType..Use the following

    $q(':input','#myform').not('#accountType').val('').removeAttr('checked').removeAttr('selected');
    
    0 讨论(0)
提交回复
热议问题