问题说明

input 标签中的 reset 按钮有重置表单的效果,比如,将 text、password textarea 用户输入的内容清空,将单选、多选等恢复默认选择状态等。

一般的表单提交不会用到 reset 按钮,要么提交,要么取消。最近有一需求,需要表单中存在重置按钮。但点击 reset 按钮,表单并没有被重置。

原因分析

网上找到了 reset 不能清空的原因:reset 重置是将表单中的元素标签恢复到初始值或初始状态,当表单中的元素标签存在 value、checked、selected 等属性,reset 重置会恢复到这些属性定义的值或者状态。

首先,reset 必须得在 form 表单内才能生效,其次,input 输入类型的元素标签不能设置默认的 value 值,checkbox、radio 不能设置默认的 checked 选中属性,select 的 option 选择项不能设置 selected 属性值。否则 reset 就达不到置空的效果。

当然,像 php 这样可以嵌入 HTML 的写法中,一般会设置默认值或默认状态,这时候只能通过 js(jQuery) 脚本来清空了。

$('input[type="reset"]').click(function () {
    $('input[type="text"]').removeAttr('value');
    $('input[type="password"]').removeAttr('value');
    $('input[type="checkbox"]').removeAttr('checked');
    $('input[type="radio"]').removeAttr('checked');
    $('select option').removeAttr('selected');
});

这里使用 removeAttr 删除属性,而不是设置 value 为空字串 ,是因为 reset 按钮本身还绑定了 $('form')[0].reset() 方法。绑定点击事件先执行,将 value 值设置为空字串,然后执行表单重置,value 值又恢复成了原来的,就相当于没改。所以,必须要使用 removeAttr 删除属性才能生效。

[notice]查找资料过程中注意到,jQuery 没有自己的 form reset 方法,即 $('form').reset() 不存在,会报错。可以使用 DOM 的 reset 方法来重置表单:$('form')[0].reset()。[/notice]

文章目录