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

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

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

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

请TIA帮忙。


当前回答

以下是我的解决方案,它也适用于新的html5输入类型:

/**
 * removes all value attributes from input/textarea/select-fields the element with the given css-selector
 * @param {string} ele css-selector of the element | #form_5
 */
function clear_form_elements(ele) {
    $(ele).find(':input').each(function() {
        switch (this.type) {
            case 'checkbox':
            case 'radio':
                this.checked = false;
            default:
                $(this).val('');
                break;
        }
    });
}

其他回答

jQuery插件

我创建了一个jQuery插件,这样我就可以在任何需要的地方轻松使用它:

jQuery.fn.clear = function()
{
    var $form = $(this);

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

    return this;
}; 

所以现在我可以通过调用:

$('#my-form').clear();

简单地这样做

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

更多的信息

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

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

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

$(this).closest('form').find('input,textarea,select').not(':image').prop('disabled', true);

我对弗朗西斯·刘易斯的解决方案做了一点改动。他的解决方案没有做的是将下拉选择设置为空白。(我认为当大多数人想要“清除”时,他们可能想让所有值为空。)这个是用。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;
};

这里刷新了复选框和选择:

$('#frm').find('input:text, input:password, input:file, textarea').val('');
$('#frm').find('input:radio, input:checkbox').attr("checked",false).checkboxradio("refresh");
$('#frm').find('select').val('').selectmenu('refresh');