元素创建多选框,通过JavaScript监听事件并处理选中状态。
当前位置:首页 > JavaScript

js 实现多选

2026-04-05 07:15:20JavaScript

实现多选框的基本方法

使用HTML的<input type="checkbox">元素创建多选框,通过JavaScript监听事件并处理选中状态。

<input type="checkbox" id="option1" value="Option 1">
<label for="option1">Option 1</label>
<input type="checkbox" id="option2" value="Option 2">
<label for="option2">Option 2</label>
document.querySelectorAll('input[type="checkbox"]').forEach(checkbox => {
  checkbox.addEventListener('change', function() {
    if (this.checked) {
      console.log(this.value + ' is selected');
    }
  });
});

获取所有选中项的值

通过遍历所有多选框,筛选出被选中的项并收集它们的值。

function getSelectedValues() {
  const selected = [];
  document.querySelectorAll('input[type="checkbox"]:checked').forEach(checkbox => {
    selected.push(checkbox.value);
  });
  return selected;
}

全选与反选功能

添加一个“全选”复选框来控制其他多选框的状态。

js 实现多选

<input type="checkbox" id="selectAll">
<label for="selectAll">Select All</label>
document.getElementById('selectAll').addEventListener('change', function() {
  const checkboxes = document.querySelectorAll('input[type="checkbox"]:not(#selectAll)');
  checkboxes.forEach(checkbox => {
    checkbox.checked = this.checked;
  });
});

使用事件委托优化性能

对于大量多选框,使用事件委托减少事件监听器的数量。

document.addEventListener('change', function(event) {
  if (event.target.matches('input[type="checkbox"]')) {
    console.log(event.target.value + ' state changed');
  }
});

与框架结合使用

在Vue中实现多选功能。

js 实现多选

new Vue({
  el: '#app',
  data: {
    options: [
      { id: 1, value: 'Option 1', checked: false },
      { id: 2, value: 'Option 2', checked: false }
    ]
  },
  computed: {
    selectedOptions() {
      return this.options.filter(option => option.checked);
    }
  }
});

样式自定义

使用CSS自定义多选框的外观。

input[type="checkbox"] {
  appearance: none;
  width: 20px;
  height: 20px;
  border: 2px solid #ccc;
  border-radius: 4px;
}

input[type="checkbox"]:checked {
  background-color: #2196F3;
  border-color: #2196F3;
}

表单提交处理

在表单提交时获取所有选中的值。

document.querySelector('form').addEventListener('submit', function(event) {
  event.preventDefault();
  const selected = getSelectedValues();
  console.log('Selected items:', selected);
});

标签: 多选js
分享给朋友:

相关文章

js实现tab选项卡切换

js实现tab选项卡切换

实现Tab选项卡切换的JavaScript方法 使用纯JavaScript实现Tab切换功能,可以通过监听点击事件动态切换内容显示状态。以下是两种常见实现方式: 基础DOM操作实现 /…

js实现防洪

js实现防洪

防抖(Debounce)实现 防抖的核心思想是在事件触发后延迟执行回调函数,若在延迟时间内再次触发事件,则重新计时。适用于输入框搜索、窗口调整等场景。 function debounce(func,…

js实现密码

js实现密码

密码强度验证 使用正则表达式验证密码强度是一种常见方法。以下代码检查密码是否包含大小写字母、数字和特殊字符,且长度至少为8位: function checkPasswordStrength(pass…

js节流实现

js节流实现

节流的概念 节流(Throttle)是一种限制函数执行频率的技术,确保函数在一定时间间隔内只执行一次。常用于滚动事件、窗口调整等高频触发的场景。 基础实现方法 使用时间戳判断是否执行函数:…

jquery 多选

jquery 多选

jQuery 多选实现方法 使用 prop() 方法实现多选 通过 prop() 方法可以批量设置多个复选框的选中状态。以下是一个示例代码: $('input[type="checkbox"]').…

js实现div隐藏

js实现div隐藏

使用CSS的display属性隐藏div 通过设置元素的display属性为none,可以完全隐藏div元素。这种方法不仅隐藏元素,还会从文档流中移除,不占据页面空间。 document.getEl…