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

如何使用JQuery实现选中两个复选框时自动选中其间所有复选框?

实现复选框区间批量选中(基于jQuery)

当然可以!这个需求用jQuery实现起来非常直观,我给你两种方案——一种严格匹配你描述的「选中两个特定复选框时自动选中中间项」,另一种是更符合用户操作习惯的「Shift键批量选区间」,你可以按需选用:

基础实现:选中两个复选框时自动填充区间

首先是你的原始HTML结构:

<input type="checkbox" name="data[]" value="1" />1 
<input type="checkbox" name="data[]" value="2" />2 
<input type="checkbox" name="data[]" value="3" />3 
<input type="checkbox" name="data[]" value="4" />4 
<input type="checkbox" name="data[]" value="5" />5 
<input type="checkbox" name="data[]" value="6" />6 
<input type="checkbox" name="data[]" value="7" />7 
<input type="checkbox" name="data[]" value="8" />8 
<input type="checkbox" name="data[]" value="9" />9 
<input type="checkbox" name="data[]" value="10" />10

然后是jQuery逻辑代码:

$(document).ready(function() {
  // 存储当前选中的复选框元素
  let checkedBoxes = [];

  $('input[name="data[]"]').on('change', function() {
    // 更新选中列表
    checkedBoxes = $('input[name="data[]"]:checked').get();

    // 当恰好选中2个复选框时触发区间选中逻辑
    if (checkedBoxes.length === 2) {
      // 获取两个选中框在所有同name复选框中的位置索引
      const firstIndex = $('input[name="data[]"]').index(checkedBoxes[0]);
      const secondIndex = $('input[name="data[]"]').index(checkedBoxes[1]);
      
      // 确定区间的起始和结束位置(兼容先选后、后选先的情况)
      const startPos = Math.min(firstIndex, secondIndex);
      const endPos = Math.max(firstIndex, secondIndex);

      // 选中区间内的所有复选框
      $('input[name="data[]"]').slice(startPos, endPos + 1).prop('checked', true);

      // 更新选中列表,避免后续操作出错
      checkedBoxes = $('input[name="data[]"]:checked').get();
    }
  });
});

代码逻辑说明:

  • 用checkedBoxes数组跟踪当前选中的复选框,每次复选框状态变化时更新这个列表。
  • 当选中数量恰好为2时,计算两个选中框的位置,自动选中它们之间的所有选项(不管用户先选哪个,都能正确识别区间)。
  • 最后更新选中列表,确保后续交互的准确性。

优化交互:Shift键批量选中/取消区间

如果想要更贴近日常操作习惯(比如和Windows文件管理器、浏览器多选逻辑一致),可以用Shift键来触发区间选择,代码如下:

$(document).ready(function() {
  // 记录最后一次选中的复选框
  let lastCheckedBox;

  $('input[name="data[]"]').on('click', function(e) {
    // 只有按住Shift键,且存在上一次选中的框时才触发区间逻辑
    if (e.shiftKey && lastCheckedBox) {
      const currentIndex = $('input[name="data[]"]').index(this);
      const lastIndex = $('input[name="data[]"]').index(lastCheckedBox);
      
      // 确定区间范围
      const start = Math.min(currentIndex, lastIndex);
      const end = Math.max(currentIndex, lastIndex);

      // 让区间内的复选框和当前点击的框保持相同选中状态(支持选中/取消)
      $('input[name="data[]"]').slice(start, end + 1).prop('checked', this.checked);
    }

    // 更新最后一次选中的框(仅当当前框被选中时更新,可根据需求调整)
    if (this.checked) {
      lastCheckedBox = this;
    }
  });
});

交互说明:

  1. 先选中任意一个复选框(比如第2个)。
  2. 按住Shift键,点击另一个复选框(比如第7个),两个框之间的所有选项会自动被选中。
  3. 如果按住Shift点击已选中的框,还可以批量取消区间内的选中状态,非常灵活。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:31:08