如何让一个Reset按钮同时清空HTML表单输入与verdict内容?
解决表单Reset按钮无法清空div内容的问题
原生的<input type="reset">只会重置表单内的标准表单控件(如input、select等),不会处理div这类非表单元素的内容,所以得自定义重置逻辑,下面是具体实现方法:
实现步骤
- 将原生reset按钮替换为普通按钮,或给它绑定自定义点击事件
- 编写JavaScript函数,同时完成表单重置和清空verdict区域内容两个操作
修改后的完整代码
<form name="myform"> <table border="5px solid" border-color="black #444 #888 #ccc" width="50%" cellpadding="1" cellspacing="1" class="table-striped" style="margin-right: calc(25%); margin-left: 10px; width: 80%;"> <tbody> <tr></tr> <tr> <td style="width: 92.7258%;"> <br> Enter the estimate $ <input maxlength="10" size="5" name="b" value=""> <br> The amount from the letter $ <input maxlength="10" size="5" name="c" value=""> <br> The number of months, enter 12 for a full year. <input maxlength="2" size="5" name="d" value=""> <br> Enter the quote amount. $ <input maxlength="10" size="5" name="e" value=""> <p></p> <input onclick="perc1()" type="button" value="Calculate"> <!-- 替换原生reset为自定义按钮 --> <input type="button" value="Reset" onclick="resetForm()"> <br> <div id="verdict"> <br> </td> </tr> </tbody> </table> </form> <script> function resetForm() { // 调用原生方法重置表单,清空所有input输入内容 document.forms['myform'].reset(); // 清空verdiv区域内容,还原为初始状态 document.getElementById('verdict').innerHTML = '<br>'; } </script>
代码说明
document.forms['myform'].reset():复用原生表单重置逻辑,一键清空所有用户输入的表单控件内容document.getElementById('verdict').innerHTML = '<br>':将verdict区域的内容还原为你初始设置的<br>,如果初始有其他默认内容,可自行调整这里的赋值内容
内容的提问来源于stack exchange,提问作者Js Smith
相关产品推荐
相关产品推荐

