js实现重置
重置表单
使用 reset() 方法可以直接重置表单内的所有输入字段到默认值。适用于 <form> 元素。
document.getElementById("myForm").reset();
清空输入字段
通过遍历表单元素,将 value 属性设为空字符串。适用于需要手动清空的场景。
const form = document.getElementById("myForm");
const inputs = form.querySelectorAll("input, textarea, select");
inputs.forEach(input => {
if (input.type !== "submit" && input.type !== "button") {
input.value = "";
}
});
重置单选/复选框
将单选按钮或复选框的 checked 属性设为 false,恢复未选中状态。
const radioButtons = document.querySelectorAll('input[type="radio"]');
radioButtons.forEach(radio => {
radio.checked = false;
});
const checkboxes = document.querySelectorAll('input[type="checkbox"]');
checkboxes.forEach(checkbox => {
checkbox.checked = false;
});
重置下拉菜单
将 <select> 元素的 selectedIndex 设为 0,恢复到默认选项。
const selects = document.querySelectorAll("select");
selects.forEach(select => {
select.selectedIndex = 0;
});
使用事件监听
通过按钮点击事件触发重置逻辑,结合上述方法实现完整功能。

document.getElementById("resetButton").addEventListener("click", () => {
document.getElementById("myForm").reset();
// 补充其他需要重置的字段逻辑
});
注意事项
- 表单重置不会触发
change或input事件,需手动处理相关逻辑。 - 密码字段在重置后可能保留浏览器自动填充的值,需额外处理。






