用于清除表单所有字段的 jQuery/Javascript 函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6653556/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 22:38:28  来源:igfitidea点击:

jQuery/Javascript function to clear all the fields of a form

javascriptjquery

提问by DiegoP.

I am looking for a jQuery function that will clear all the fields of a form after having submitted the form.

我正在寻找一个 jQuery 函数,它将在提交表单后清除表单的所有字段。

I do not have any HTML code to show, I need something generic.

我没有要显示的任何 HTML 代码,我需要一些通用的东西。

Can you help?

你能帮我吗?

Thanks!

谢谢!

回答by Jason McCreary

Note: this answer is relevant to resetting form fields, not clearing fields - see update.

注意:此答案与重置表单字段有关,而不是清除字段 - 请参阅更新。

You can use JavaScript's native reset()method to resetthe entire form to its defaultstate.

您可以使用 JavaScript 的本机reset()方法将整个表单重置为其默认状态。

Example provided by Ryan:

Ryan提供的示例:

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

Note:This may not reset certain fields, such as type="hidden".

注意:这可能不会重置某些字段,例如type="hidden"

UPDATE

更新

As noted by IlyaDoroshinthe same thing can be accomplished using jQuery's trigger():

正如IlyaDoroshin所指出的,同样的事情可以使用 jQuery 来完成trigger()

$('#myForm').trigger("reset");

UPDATE

更新

If you need to do more than resetthe form to its defaultstate, you should review the answers to Resetting a multi-stage form with jQuery.

如果您需要做的不仅仅是将表单重置为其默认状态,您应该查看使用 jQuery 重置多阶段表单的答案。

回答by IlyaDoroshin

To reset form (but not clear the form) just trigger resetevent:

要重置表单(但不清除表单)只需触发reset事件:

$('#form').trigger("reset");

To cleara form see other answers.

清除表单,请参阅其他答案。

回答by ktamlyn

Something similar to $("#formId").reset()will not clear form items that have had their defaults set to something other than "". One way this can happen is a previous form submission: once a form has been submitted reset()would "reset" form values to those previously submitted which will likely not be "".

类似于$("#formId").reset()不会清除默认设置为"". 发生这种情况的一种方式是先前的表单提交:一旦提交了表单,reset()就会将表单值“重置”为先前提交的值,而这些值可能不是"".

One option to clear all forms on the page, is to call a function such as the following, executing it simply as clearForms():

清除页面上所有表单的一种选择是调用如下函数,简单地执行它clearForms()

function clearForms()
{
    $(':input').not(':button, :submit, :reset, :hidden, :checkbox, :radio').val('');
    $(':checkbox, :radio').prop('checked', false);
}

If you want to reset a specific form, then modify the function as follows, and call it as clearForm($("#formId")):

如果你想重置一个特定的表单,那么修改函数如下,并调用它clearForm($("#formId"))

function clearForm($form)
{
    $form.find(':input').not(':button, :submit, :reset, :hidden, :checkbox, :radio').val('');
    $form.find(':checkbox, :radio').prop('checked', false);
}

When I originally came to this page I needed a solution that takes into account form defaults being changed and is still able to clear all input items.

当我最初来到这个页面时,我需要一个解决方案,该解决方案考虑到正在更改的表单默认值并且仍然能够清除所有输入项。

Note that this will not clear placeholdertext.

请注意,这不会清除placeholder文本。

回答by Stanley Cup Phil

Set the valto ""

设置val为“”

function clear_form_elements(ele) {

        $(ele).find(':input').each(function() {
            switch(this.type) {
                case 'password':
                case 'select-multiple':
                case 'select-one':
                case 'text':
                case 'textarea':
                    $(this).val('');
                    break;
                case 'checkbox':
                case 'radio':
                    this.checked = false;
            }
        });

    }

<input onclick="clear_form_elements(this.form)" type="button" value="Clear All" />  
<input onclick="clear_form_elements('#example_1')" type="button" value="Clear Section 1" />
<input onclick="clear_form_elements('#example_2')" type="button" value="Clear Section 2" />
<input onclick="clear_form_elements('#example_3')" type="button" value="Clear Section 3" />

You could also try something like this:

你也可以尝试这样的事情:

  function clearForm(form) {

    // iterate over all of the inputs for the form

    // element that was passed in

    $(':input', form).each(function() {

      var type = this.type;

      var tag = this.tagName.toLowerCase(); // normalize case

      // it's ok to reset the value attr of text inputs,

      // password inputs, and textareas

      if (type == 'text' || type == 'password' || tag == 'textarea')

        this.value = "";

      // checkboxes and radios need to have their checked state cleared

      // but should *not* have their 'value' changed

      else if (type == 'checkbox' || type == 'radio')

        this.checked = false;

      // select elements need to have their 'selectedIndex' property set to -1

      // (this works for both single and multiple select elements)

      else if (tag == 'select')

        this.selectedIndex = -1;

    });

  };

More info hereand here

更多信息在这里这里

回答by genesis

    <form id="form" method="post" action="action.php">
      <input type="text" class="removeLater" name="name" /> Username<br/>
      <input type="text" class="removeLater" name="pass" /> Password<br/>
      <input type="text" class="removeLater" name="pass2" /> Password again<br/>
    </form>
    <script>
$(function(){
    $("form").submit(function(e){
         //do anything you want
         //& remove values
         $(".removeLater").val('');
    }

});
</script>

回答by Eduardo M

You can simply use the resetbutton type.

您可以简单地使用reset按钮类型。

<input type="text" />
<input type="reset" />

jsfiddle

提琴手

Edit:Remember that, the resetbutton, reset the form for the original values, so, if the field has some value set on the field <input type="text" value="Name" />after press resetthe field will reset the value inserted by user and come back with the word "name" in this example.

编辑:请记住,该reset按钮将表单重置为原始值,因此,如果该字段<input type="text" value="Name" />在按下reset该字段后在该字段上设置了一些值,则该字段将重置用户插入的值并在此返回“名称”一词例子。

Reference: http://api.jquery.com/reset-selector/

参考:http: //api.jquery.com/reset-selector/

回答by rusllonrails

I use following solution:

我使用以下解决方案:

1) Setup Jquery Validation Plugin

1) 设置Jquery 验证插件

2) Then:

2)然后:

$('your form's selector').resetForm();

回答by Shaun Forsyth

the trigger idea was smart, however I wanted to do it the jQuery way, so here is a small function which will allow you to keep chaining.

触发的想法很聪明,但是我想用 jQuery 的方式来做,所以这里有一个小函数,它可以让你继续链接。

$.fn.resetForm = function() {
    return this.each(function(){
        this.reset();
    });
}

Then just call it something like this

然后就这样称呼它

$('#divwithformin form').resetForm();

or

或者

$('form').resetForm();

and of course you can still use it in the chain

当然你仍然可以在链中使用它

$('form.register').resetForm().find('input[type="submit"]').attr('disabled','disabled')

回答by TheRealJAG

function reset_form() {
 $('#ID_OF_FORM').each (function(){  
    this.reset();
 }); 
}

回答by Brian Hoover

Would something like work?

喜欢工作吗?

JQuery Clear Form on close

关闭时的 JQuery 清除表单