HTML 結構
核心操作方法
1. 獲取選中值 - 原生 JS 兩種方式
// 方式一:遍歷 NodeList
function getSelectedValueByName(name) {
const radios = document.getElementsByName(name);
for (const radio of radios) {
if (radio.checked) return radio.value;
}
return null;
}
// 方式二:通過表單元素集合
function getSelectedValueByForm(formId, name) {
const form = document.getElementById(formId);
const radios = form.elements[name]; // RadioNodeList
return radios.value; // 直接返回選中值 (HTML5 標準)
}
2. 設置選中狀態
// 按值設置
function setRadioValue(name, value) {
const radios = document.getElementsByName(name);
for (const radio of radios) {
radio.checked = (radio.value === value);
}
}
// 按索引設置
function setRadioIndex(name, index) {
const radios = document.getElementsByName(name);
if (radios[index]) radios[index].checked = true;
}
3. jQuery 簡化寫法
// 獲取值
const val = $('input[name="opinionCategory"]:checked').val();
// 設置值
$('input[name="opinionCategory"][value="1"]').prop('checked', true);
// 事件監聽 (委託動態元素)
$(document).on('change', 'input[name="opinionCategory"]', function() {
console.log('選中值:', this.value);
});
進階場景處理
表單提交前驗證
function validateRadioGroup(name, required = true) {
const selected = document.querySelector(`input[name="${name}"]:checked`);
if (required && !selected) {
alert(`請選擇 ${name}`);
return false;
}
return true;
}
動態生成單選組
function createRadioGroup(containerId, name, options, defaultValue) {
const container = document.getElementById(containerId);
container.innerHTML = options.map((opt, i) => `
`).join('');
}
常見問題避坑
- name 屬性必須一致:同組單選框 name 相同才能互斥
- value 為空字符串:未選中時
form.elements[name].value 返回空串而非 null
- 標籤關聯:使用
<label> 包裹或 for 屬性關聯,提升點擊區域
- 重置表單:
form.reset() 會恢復到初始 checked 狀態
現代框架綁定
<!-- Vue 3 -->
<input type="radio" v-model="selected" value="1">
<input type="radio" v-model="selected" value="0">
<!-- React -->
<input type="radio" name="opt" value="1" checked={val==='1'} onChange={e=>setVal(e.target.value)} />