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

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

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

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

请TIA帮忙。


当前回答

清除表单有点棘手,不像看起来那么简单。

建议你使用jQuery表单插件,并使用它的clearForm或resetForm功能。 它能解决大部分的极端情况。

其他回答

我使用下面的解决方案,它为我工作(混合传统javascript和jQuery)

$("#myformId").submit(function() {
    comand="window.document."+$(this).attr('name')+".reset()";
    setTimeout("eval(comando)",4000);
})

我对保罗·伯甘蒂诺最初的回答做了一点改进

function resetFormInputs(context) {
    jQuery(':input', context)
    .removeAttr('checked')
    .removeAttr('selected')
    .not(':button, :submit, :reset, :hidden')
    .each(function(){
         jQuery(this).val(jQuery(this).prop('defautValue'));
    });
}

通过这种方式,我可以将任何上下文元素传递给函数。我能够重置整个表单或仅某一组字段,例如:

resetFormInputs('#form-id'); // entire form
resetFormInputs('.personal-info'); // only the personal info field set

另外,输入的默认值将被保留。

对paolo的答案进行了轻微的更新,以适应新的输入类型,如“tel”和电子邮件,以下代码片段也将选择这些类型:

function resetForm(form) {
    form.find('input:text, input[type=email], input[type=tel], input:password, input:file, select, textarea').val('');
    form.find('input:radio, input:checkbox')
         .removeAttr('checked').removeAttr('selected');
}

简单地这样做

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

更多的信息

如果你有这样的输入,设置myinput.val(")可能不能100%模拟"reset":

<input name="percent" value="50"/>

例如,在一个默认值为50的输入上调用myinput.val(")会将其设置为空字符串,而调用myform.reset()则会将其重置为初始值50。

A method I used on a fairly large form (50+ fields) was to just reload the form with AJAX, basically making a call back to the server and just returning the fields with their default values. This made is much easier than trying to grab each field with JS and then setting it to it's default value. It also allowed to me to keep the default values in one place--the server's code. On this site, there were also some different defaults depending on the settings for the account and therefore I didn't have to worry about sending these to JS. The only small issue I had to deal with were some suggest fields that required initialization after the AJAX call, but not a big deal.