js实现多次单选
使用事件监听实现多次单选
在HTML中创建多个单选按钮组,确保每组有相同的name属性。通过JavaScript监听change事件,动态更新选中状态。
<div class="radio-group">
<input type="radio" name="group1" value="option1"> Option 1
<input type="radio" name="group1" value="option2"> Option 2
</div>
<div class="radio-group">
<input type="radio" name="group2" value="optionA"> Option A
<input type="radio" name="group2" value="optionB"> Option B
</div>
document.querySelectorAll('.radio-group input[type="radio"]').forEach(radio => {
radio.addEventListener('change', function() {
console.log(`Selected: ${this.value} from group ${this.name}`);
});
});
动态生成单选按钮组
通过JavaScript动态创建多个单选按钮组,并自动处理选中逻辑。
function createRadioGroups(groupsData) {
const container = document.getElementById('radioContainer');
groupsData.forEach((group, index) => {
const groupDiv = document.createElement('div');
groupDiv.className = 'radio-group';
group.options.forEach(option => {
const radio = document.createElement('input');
radio.type = 'radio';
radio.name = `group${index}`;
radio.value = option.value;
radio.id = `group${index}_${option.value}`;
const label = document.createElement('label');
label.htmlFor = radio.id;
label.textContent = option.label;
groupDiv.appendChild(radio);
groupDiv.appendChild(label);
});
container.appendChild(groupDiv);
});
}
const sampleData = [
{ options: [
{ value: 'a', label: 'Choice A' },
{ value: 'b', label: 'Choice B' }
]},
{ options: [
{ value: 'x', label: 'Choice X' },
{ value: 'y', label: 'Choice Y' }
]}
];
createRadioGroups(sampleData);
存储和检索选择结果
使用对象来存储用户在各个单选组中的选择,并提供方法获取完整选择结果。
const selections = {};
document.querySelectorAll('.radio-group').forEach(group => {
const radios = group.querySelectorAll('input[type="radio"]');
const groupName = radios[0]?.name;
radios.forEach(radio => {
radio.addEventListener('change', function() {
if (this.checked) {
selections[groupName] = this.value;
}
});
});
});
function getAllSelections() {
return selections;
}
表单提交处理
在表单提交时收集所有单选组的选择结果,并阻止默认提交行为进行自定义处理。
document.getElementById('myForm').addEventListener('submit', function(e) {
e.preventDefault();
const formData = {};
document.querySelectorAll('.radio-group').forEach(group => {
const selected = group.querySelector('input[type="radio"]:checked');
if (selected) {
formData[selected.name] = selected.value;
}
});
console.log('Form data:', formData);
// 这里可以添加AJAX提交或其他处理逻辑
});
响应式单选按钮组
结合CSS实现视觉反馈,增强用户体验。
.radio-group {
margin: 15px 0;
padding: 10px;
border: 1px solid #ddd;
border-radius: 5px;
}
input[type="radio"]:checked + label {
font-weight: bold;
color: #0066cc;
}






