萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

jQuery 操作 Radio 按鈕完整實戰:取值、設值、驗證與動態綁定

HTML 結構範例

<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 群組值的通用函數

/**
 * 取得 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 群組值的通用函數

/**
 * 設定 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');

動態新增 radio 選項

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
  • 動態新增:新增後的 radio 事件綁定請用 .on() 委派或重新綁定
  • 重置表單:$('form')[0].reset() 可將 radio 恢復預設勾選

總結

掌握 :radio:checked、:radio、:text 三大選擇器,搭配 .val()、.each()、原生 .checked,即可輕鬆應對所有 radio 操作場景。封裝通用函數讓業務代碼更乾淨。

copyright © 萬盛學電腦網 all rights reserved