js实现单选多选
实现单选功能
在HTML中创建单选按钮组,确保同一组的name属性相同。通过JavaScript监听change事件获取选中值。
<input type="radio" name="gender" value="male"> Male
<input type="radio" name="gender" value="female"> Female
document.querySelectorAll('input[name="gender"]').forEach(radio => {
radio.addEventListener('change', function() {
if (this.checked) {
console.log('Selected:', this.value);
}
});
});
实现多选功能
使用checkbox类型输入元素,通过JavaScript获取所有被选中的值。
<input type="checkbox" name="fruit" value="apple"> Apple
<input type="checkbox" name="fruit" value="banana"> Banana
<input type="checkbox" name="fruit" value="orange"> Orange
document.querySelector('button').addEventListener('click', function() {
const selected = [];
document.querySelectorAll('input[name="fruit"]:checked').forEach(checkbox => {
selected.push(checkbox.value);
});
console.log('Selected:', selected);
});
使用事件委托优化性能
为父元素添加单个事件监听器处理所有单选/多选事件,适合动态生成的选项。
document.getElementById('radioGroup').addEventListener('change', function(e) {
if (e.target.type === 'radio') {
console.log('Radio selected:', e.target.value);
}
});
表单提交处理
在表单提交时收集所有选择结果,可通过FormDataAPI简化操作。
document.getElementById('myForm').addEventListener('submit', function(e) {
e.preventDefault();
const formData = new FormData(this);
// 获取单选值
const gender = formData.get('gender');
// 获取多选值数组
const fruits = formData.getAll('fruit');
console.log({gender, fruits});
});
动态生成选项
通过JavaScript动态创建单选/多选按钮并绑定事件。

const options = ['Red', 'Green', 'Blue'];
const container = document.getElementById('colorOptions');
options.forEach(color => {
const checkbox = document.createElement('input');
checkbox.type = 'checkbox';
checkbox.name = 'colors';
checkbox.value = color.toLowerCase();
const label = document.createElement('label');
label.appendChild(checkbox);
label.appendChild(document.createTextNode(color));
container.appendChild(label);
});






