<div class="radio-group">
<label><input name="study" type="radio" value="jquery-plugin"> jQuery 插件教程</label>
<label><input name="study" type="radio" value="jquery-learn"> jQuery 學習</label>
<label><input name="study" type="radio" value="php-learn"> PHP 學習</label>
</div>
<button id="submitBtn">確定</button>
<button id="setJquery" title="jquery-learn">設定為 jQuery 學習</button>
<button id="viewText">查看同名 text 值</button>
<input name="study" type="text" value="請輸入想學的知識" />
| 需求 | 選擇器 | 說明 |
|---|---|---|
| 取得被選中的 radio | $('input[name="study"]:radio:checked') | :radio 等同 [type=radio] |
| 取得所有同名 radio | $('input[name="study"]:radio') | |
| 取得同名 text 欄位 | $('input[name="study"]:text') | :text 等同 [type=text] |
$(function() {
// 1. 提交:驗證是否選擇 + 取值
$('#submitBtn').click(function() {
var $checked = $('input[name="study"]:radio:checked');
if ($checked.length === 0) {
alert('請選擇您想學習的知識');
return;
}
var val = $checked.val();
alert('謝謝!您選擇的是:' + val);
});
// 2. 程式化設值:依 value 選中
$('#setJquery').click(function() {
var targetVal = $(this).attr('title'); // 'jquery-learn'
$('input[name="study"]:radio').each(function() {
if (this.value === targetVal) {
this.checked = true; // 原生屬性最直接
return false; // 跳出 each
}
});
});
// 3. 區分同名不同型別:取 text 值
$('#viewText').click(function() {
var textVal = $('input[name="study"]:text').val();
alert('Text 欄位值:' + textVal);
});
});
/**
* 取得 radio 群組選中值
* @param {string} name - radio name 屬性
* @returns {string|undefined} 選中值或 undefined
*/
function getRadioValue(name) {
return $('input[name="' + name + '"]:radio:checked').val();
}
// 使用
var study = getRadioValue('study');
/**
* 設定 radio 群組選中項
* @param {string} name
* @param {string} value
* @returns {boolean} 是否找到並設定成功
*/
function setRadioValue(name, value) {
var $radios = $('input[name="' + name + '"]:radio');
var found = false;
$radios.each(function() {
if (this.value === value) {
this.checked = true;
found = true;
return false;
}
});
return found;
}
// 使用
setRadioValue('study', 'php-learn');
function addRadioOption(name, value, label, checked) {
var $container = $('input[name="' + name + '"]:radio').first().parent().parent();
var $label = $('
input[name="study"] 會同時選中 radio 和 text,務必加 :radio 或 :text 過濾.val() 於 radio 群組:僅回傳被選中項的值,未選中回傳 undefined.on() 委派或重新綁定$('form')[0].reset() 可將 radio 恢復預設勾選掌握 :radio:checked、:radio、:text 三大選擇器,搭配 .val()、.each()、原生 .checked,即可輕鬆應對所有 radio 操作場景。封裝通用函數讓業務代碼更乾淨。