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:21

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>
查看更多
妖精总统
3楼-- · 2019-01-01 05:22

if you use selectors and make values to empty values, it is not resetting the form, it's making all fields empty. Reset is to make form as it was before any edit actions from user after the load of form from server side. If there is an input with name "username" and that username was prefilled from server side, most of solutions on this page will delete that value from input, not reset it to the value how it was before user's changes. If you need to reset the form, use this:

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

if you need not to reset the form, but fill all inputs with some value, for example empty value, then you can use most of the solutions from other comments.

查看更多
唯独是你
4楼-- · 2019-01-01 05:22

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.

查看更多
登录 后发表回答