我有一个标准的重置按钮的形式编码如下:

<input type="reset" class="button standard" value="Clear" />

问题是,所述表单是多阶段排序的,所以如果用户填写了一个阶段,然后稍后返回,当单击Clear按钮时,各个字段的“记住”值不会重置。

我在想,附加一个jQuery函数循环所有的字段和清除他们'手动'将做的技巧。我已经在使用jQuery的形式,但我只是刚刚赶上速度&所以我不知道如何做到这一点,除了单独引用每个字段的ID,这似乎不是很有效。

请TIA帮忙。


当前回答

考虑使用验证插件——它很棒!重置表单很简单:

var validator = $("#myform").validate();
validator.resetForm();

其他回答

所有这些答案都很好,但最简单的方法是使用虚假重置,即使用链接和重置按钮。

只需添加一些CSS来隐藏你真正的重置按钮。

input[type=reset] { visibility:hidden; height:0; padding:0;}

然后在你的链接上添加如下内容

<a href="javascript:{}" onclick="reset.click()">Reset form</a>

<input type="reset" name="reset" id="reset" /><!--This input button is hidden-->

希望这能有所帮助! 一个。

2012年3月更新。

所以,在我最初回答这个问题的两年后,我回头看看,它已经变成了一个大混乱。我觉得是时候回到这个问题上来,让我的答案真正正确了,因为它得到了最多的好评和接受。

For the record, Titi's answer is wrong as it is not what the original poster asked for - it is correct that it is possible to reset a form using the native reset() method, but this question is trying to clear a form off of remembered values that would remain in the form if you reset it this way. This is why a "manual" reset is needed. I assume most people ended up in this question from a Google search and are truly looking for the reset() method, but it does not work for the specific case the OP is talking about.

我最初的回答是这样的:

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

这可能适用于许多情况,包括OP,但正如评论和其他回答中指出的那样,将从任何值属性中清除单选/复选框元素。

一个更正确(但不完美)的答案是:

function resetForm($form) {
    $form.find('input:text, input:password, input:file, select, textarea').val('');
    $form.find('input:radio, input:checkbox')
         .removeAttr('checked').removeAttr('selected');
}

// to call, use:
resetForm($('#myform')); // by id, recommended
resetForm($('form[name=myName]')); // by name

jQuery认为,单独使用:text、:radio等选择器是一种糟糕的做法,因为它们最终会求值为*:text,这会花费比正常情况下更长的时间。我确实更喜欢白名单的方法,希望我在最初的回答中使用了它。无论如何,通过指定选择器的输入部分,加上表单元素的缓存,这应该使它成为这里性能最好的答案。

如果人们默认的选择元素不是一个空值的选项,那么这个答案可能仍然有一些缺陷,但它肯定是通用的,这将需要根据具体情况进行处理。

简单地使用jQuery触发器事件,如下所示:

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

这将重置复选框,单选按钮,文本框等…本质上,它会将表单转换为默认状态。简单地把#ID, Class,元素放在jQuery选择器中。

补充接受的答案,如果你使用SELECT2插件,你需要召回SELECT2脚本来更改所有的SELECT2字段:

function resetForm(formId){
        $('#'+formId).find('input:text, input:password, input:file, select, select2, textarea').val('');
        $('#'+formId).find('input:radio, input:checkbox').removeAttr('checked').removeAttr('selected');
        $('.select2').select2();
    }

我通常这样做:

$('#formDiv form').get(0).reset()

or

$('#formId').get(0).reset()