如何调用form.reset()时保留select的选中状态?
解决方法:修改select的默认选中项匹配当前状态
和input的defaultValue原理完全对应,select的默认选中状态是由每个<option>的defaultSelected属性控制的。你只需要在调用form.reset()之前,把当前选中的option的defaultSelected设为true,同时把其他option的defaultSelected设为false,这样执行reset时,select就会保持当前选中的状态。
修改后的按钮点击事件代码如下:
button.addEventListener('click', function () { // 保存当前选中的option const currentSelectedOption = selector.options[selector.selectedIndex]; // 遍历所有option,更新默认选中标记 for (let option of selector.options) { option.defaultSelected = option === currentSelectedOption; } // 调用reset,select会保持当前选中状态 form.reset(); });
原理说明
- 页面加载时,浏览器会自动把第一个没有
selected属性的option的defaultSelected设为true,这就是select的「默认选中项」。 form.reset()的逻辑是将表单元素恢复到初始默认状态:input用defaultValue覆盖当前value,select则会选中defaultSelected为true的option。- 我们提前把当前选中的option设为默认项,这样reset后select就不会变回初始状态,和你设置
inputText.defaultValue = inputText.value的思路完全一致。
如果你的需求是同时保留文本框和select的当前状态,结合你原来的方法即可:
button.addEventListener('click', function () { // 保留文本框的值:将当前值设为默认值 inputText.defaultValue = inputText.value; // 保留select的选中状态:将当前选中项设为默认选中项 const currentSelectedOption = selector.options[selector.selectedIndex]; for (let option of selector.options) { option.defaultSelected = option === currentSelectedOption; } // 调用reset,两个元素都会保持当前状态 form.reset(); });
内容的提问来源于stack exchange,提问作者pmA
相关产品推荐
相关产品推荐

