You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过JavaScript在HTML表单重置或点击取消按钮时恢复选中选项至初始状态

实现Select元素重置,恢复初始选中值

要解决用户修改select选项后,点击重置按钮恢复到系统初始选中状态的问题,分两种场景处理:

场景1:Select在表单内

如果你的select元素是放在<form>标签里的,直接使用原生重置按钮即可,浏览器会自动恢复所有表单控件的初始值,无需额外JS代码:

<form id="myForm">
  <button type="reset">Reset</button>
  <select>
    <option>1</option>
    <option>2</option>  
    <option>3</option>
  </select>

  <select class="jbselect">
    <option>a</option>
    <option>b</option>
    <option selected>c</option>
  </select>
</form>

这里type="reset"的按钮会触发表单重置事件,自动将select恢复到页面加载时的初始状态——未设置selected属性的select默认选中第一个选项,设置了selected的则回到指定选项。

场景2:Select不在表单内

如果没有表单包裹,需要手动记录每个select的初始状态,点击重置时恢复:

修改后的HTML(给元素加标识方便操作)

<button id="resetBtn">Reset</button>
<select class="reset-target">
  <option>1</option>
  <option>2</option>  
  <option>3</option>
</select>

<select class="reset-target jbselect">
  <option>a</option>
  <option>b</option>
  <option selected>c</option>
</select>

原生JS实现代码

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
  // 收集所有需要重置的select元素
  const selects = document.querySelectorAll('.reset-target');
  // 保存每个select的初始选中索引
  const initialSelectedIndexes = Array.from(selects).map(sel => sel.selectedIndex);

  // 绑定重置按钮点击事件
  document.getElementById('resetBtn').addEventListener('click', () => {
    selects.forEach((sel, index) => {
      // 恢复到初始选中索引
      sel.selectedIndex = initialSelectedIndexes[index];
    });
  });
});

代码说明

  • 页面加载时,遍历所有需要重置的select,记录它们的selectedIndex(页面初始渲染时的选中项索引)
  • 点击重置按钮时,将每个select的selectedIndex设回初始值,实现视图恢复到默认选中状态

这种方法兼容性好,无需依赖框架,适用于所有现代浏览器。

内容的提问来源于stack exchange,提问作者Jatinder

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 04:35:25