Clear form fields with jQuery

前端 未结 30 2709
甜味超标
甜味超标 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:34

    Tested and verified code:

      $( document ).ready(function() {
        $('#messageForm').submit(function(e){
           e.preventDefault();
        });
        $('#send').click(function(e){
          $("#messageForm")[0].reset();
        });
      });
    

    Javascript must be included in $(document).ready and it must be with your logic.

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

    Most easy and best solution is-
    $("#form")[0].reset();

    Don't use here -
    $(this)[0].reset();

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

    Let us say if you want to clear the fields and except accountType,in the mean time dropdown box will be reset to particular value,i.e 'All'.Remaining fields should be reset to empty i.e text box.This approach will be used for clearing particular fields as our requirement.

     $(':input').not('#accountType').each( function() {
    
        if(this.type=='text' || this.type=='textarea'){
                 this.value = '';
           }
        else if(this.type=='radio' || this.type=='checkbox'){
             this.checked=false;
          }
             else if(this.type=='select-one' || this.type=='select-multiple'){
                  this.value ='All';
         }
     });
    
    0 讨论(0)
  • 2020-11-22 16:34

    Some of you were complaining that radios and such are cleared of default "checked" status... All you have to do is add the :radio, :checkbox selectors to the .not and the problem is solved.

    If you can't get all the other reset functions to work, this one will.

    • Adapted from ngen's answer

      function form_reset(formID){
          $(':input','#'+formID)
          .not(':button',':submit',':reset',':hidden',':radio',':checkbox')
          .val('');
      }
      
    0 讨论(0)
  • 2020-11-22 16:34

    By using a combination of JQuery's .trigger() and native Javascripts's .reset() all form elements can be reset to blank state.

    $(".reset").click(function(){
        $("#<form_id>").trigger("reset");
    });
    

    Replace <form_id> with id of form to reset.

    0 讨论(0)
  • 2020-11-22 16:34
    $(document).ready(function() {
        $('#reset').click(function() {
        $('#compose_form').find("input[type=text] , textarea ").each(function() {
        $(this).val('');
       });
      });
    });  
    
    0 讨论(0)
提交回复
热议问题