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

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

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

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

请TIA帮忙。


当前回答

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

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

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

其他回答

以下是我的解决方案,它也适用于新的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;
        }
    });
}

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

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

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

这里有一些东西可以让你开始

$('form') // match your correct form 
.find('input[type!=submit], input[type!=reset]') // don't reset submit or reset
.val(''); // set their value to blank

当然,如果你有复选框/单选按钮,你将需要修改这包括他们以及设置。attr({'checked': false});

编辑 Paolo的回答更加简洁。我的回答更啰嗦,因为我不知道:input选择器,也没有想过简单地删除选中的属性。

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

我通常这样做:

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

or

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