Clear form fields with jQuery

2019-01-01 04:42发布

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").bind("click", function() {
  $("input[type=text], textarea").val("");
});

This will clear all fields on the page, not just the ones from the form. How would my selector look like for just the form the actual reset button lives in?

27条回答
人间绝色
2楼-- · 2019-01-01 05:10

Any reason this shouldn't be used?

$("#form").trigger('reset');
查看更多
明月照影归
3楼-- · 2019-01-01 05:11

For jQuery 1.6+:

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

For jQuery < 1.6:

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

Please see this post: Resetting a multi-stage form with jQuery

Or

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

As jQuery suggests:

To retrieve and change DOM properties such as the checked, selected, or disabled state of form elements, use the .prop() method.

查看更多
宁负流年不负卿
4楼-- · 2019-01-01 05:11

If you want to empty all input boxes irrespective of its type then it's a minute step by

 $('#MyFormId')[0].reset();
查看更多
无色无味的生活
5楼-- · 2019-01-01 05:12

Use this Code Where you want to Call Normal Reset Function by jQuery

setTimeout("reset_form()",2000);

And Write this Function Out Site jQuery on Document Ready

<script>
function reset_form()
{
    var fm=document.getElementById('form1');
    fm.reset();
}
</script>
查看更多
呛了眼睛熬了心
6楼-- · 2019-01-01 05:12
@using (Ajax.BeginForm("Create", "AcceptanceQualityDefect", new AjaxOptions()
{
    OnSuccess = "ClearInput",
    HttpMethod = "Post",
    UpdateTargetId = "defect-list",
    InsertionMode = InsertionMode.Replace
}, new { @id = "frmID" })) 
  1. frmID is the identification of the form
  2. OnSuccess of the operation we call the JavaScript function with the name "ClearInput"

    <script type="text/javascript">
        function ClearInput() {
            //call action for render create view
            $("#frmID").get(0).reset();
        }
    </script>
    
  3. if you do both of these right, then you will not be able to stop it from working...

查看更多
余欢
7楼-- · 2019-01-01 05:14

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';
     }
 });
查看更多
登录 后发表回答