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

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

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

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

请TIA帮忙。


当前回答

对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');
}

其他回答

我对弗朗西斯·刘易斯的解决方案做了一点改动。他的解决方案没有做的是将下拉选择设置为空白。(我认为当大多数人想要“清除”时,他们可能想让所有值为空。)这个是用。find('select')。道具(“selectedIndex”,1)。

$.fn.clear = function()
{
    $(this).find('input')
            .filter(':text, :password, :file').val('')
            .end()
            .filter(':checkbox, :radio')
                .removeAttr('checked')
            .end()
        .end()
    .find('textarea').val('')
        .end()
    .find('select').prop("selectedIndex", -1)
        .find('option:selected').removeAttr('selected')
    ;
    return this;
};

修改$(document).ready()情况投票最多的答案:

$('button[type="reset"]').click(function(e) {
    $form = $(this.form);
    $form.find('input:text, input:password, input:file, select, textarea').val('');
    $form.find('input:radio, input:checkbox').removeAttr('checked').removeAttr('selected');
    e.preventDefault();
});

这对我有用,pyrotex回答没有“重置选择字段,取他的,在这里”我的编辑:

// Use a whitelist of fields to minimize unintended side effects.
$(':text, :password, :file', '#myFormId').val('');  
// De-select any checkboxes, radios and drop-down menus
$(':input,select option', '#myFormId').removeAttr('checked').removeAttr('selected');
//this is for selecting the first entry of the select
$('select option:first', '#myFormId').attr('selected',true);

我也有同样的问题,保罗的职位帮助了我,但我需要调整一件事。我使用id advancedindexsearch的表单只包含输入字段,并从会话中获取值。出于某种原因,下面这些方法对我来说并不管用:

$("#advancedindexsearch").find("input:text").val("");

如果我在这之后放了一个警告,我看到了正确删除的值,但之后它们又被替换了。我仍然不知道为什么,但下面这句话确实对我起了作用:

$("#advancedindexsearch").find("input:text").attr("value","");

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.