HTML中不使用form表单如何让reset重置按钮正常生效
表单重置按钮实现方案
方案1:使用原生form自带的reset功能(无需写JS)
直接在form标签内部加入type为reset的button即可,会自动清空表单内所有输入项、恢复默认值:
<form id="myForm"> <!-- 你的各类表单控件,比如input、select、textarea这些 --> <input type="text" name="username" placeholder="用户名"> <input type="password" name="pwd" placeholder="密码"> <!-- 提交按钮正常写 --> <button type="submit">提交</button> <!-- 重置按钮,type设为reset即可 --> <button type="reset">重置</button> </form>
注意:如果之前你的按钮没指定type,浏览器会默认把form里的button当成submit类型,才会导致和提交功能冲突,必须显式给重置按钮加
type="reset",提交按钮加type="submit"区分。
方案2:用JS手动实现重置(适合需要自定义重置逻辑的场景)
如果你需要在重置的时候额外做其他操作(比如清空自定义的缓存、隐藏提示文字),可以用JS调用form的reset方法:
<form id="myForm"> <input type="text" name="username" placeholder="用户名"> <input type="password" name="pwd" placeholder="密码"> <button type="submit">提交</button> <!-- 这里重置按钮用普通button类型,绑定点击事件 --> <button type="button" id="resetBtn">重置</button> </form> <script> const resetBtn = document.getElementById('resetBtn') const myForm = document.getElementById('myForm') resetBtn.addEventListener('click', () => { // 调用form原生reset方法 myForm.reset() // 如果有其他自定义操作可以写在这,比如清空错误提示 // document.getElementById('errorTip').textContent = '' }) </script>
- 以上两种方案都不会影响submit提交按钮的正常功能,只要你给每个按钮都显式指定了type属性,就不会出现类型冲突的问题。
- 如果按照上面的写法还是不生效,你可以检查下是不是你的form控件没有加name属性,或者有其他JS代码阻止了按钮的默认事件。
内容的提问来源于stack exchange,提问作者NAK SUSHI
相关产品推荐
相关产品推荐

