Resetting a multi-stage form with jQuery

前端 未结 30 2604
谎友^
谎友^ 2020-11-22 00:58

I have a form with a standard reset button coded thusly:


Trouble i

30条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-22 01:16

    There's a big problem with Paolo's accepted answer. Consider:

    $(':input','#myform')
     .not(':button, :submit, :reset, :hidden')
     .val('')
     .removeAttr('checked')
     .removeAttr('selected');
    

    The .val('') line will also clear any value's assigned to checkboxes and radio buttons. So if (like me) you do something like this:

    
    
    
    

    Using the accepted answer will transform your inputs into:

    
    
    
    

    Oops - I was using that value!

    Here's a modified version that will keep your checkbox and radio values:

    // Use a whitelist of fields to minimize unintended side effects.
    $('INPUT:text, INPUT:password, INPUT:file, SELECT, TEXTAREA', '#myFormId').val('');  
    // De-select any checkboxes, radios and drop-down menus
    $('INPUT:checkbox, INPUT:radio', '#myFormId').removeAttr('checked').removeAttr('selected');
    

提交回复
热议问题