DIV CSS 佈局教程網

jQuery 取得與設定單選組 radio 值的常見寫法
編輯:關於JavaScript     

radio 的操作看起來簡單,但 jQuery 版本更迭時語法有過一次重要變化,網路上抄來的例子常常在新版直接失效。這裡把常用寫法整理清楚。

取得選中項的值

// 取得被選中的 radio 值
var item = $('input[name=items]:checked').val();

設定某個項目為選中

// jQuery 1.3 之前:用 @ 前綴
$("input[@type=radio]").attr("checked", '2');

// jQuery 1.3 之後:拿掉 @
$("input[name='radio_name']").attr("checked", true);

重點:jQuery 1.3 起已移除 @ 前綴語法,寫 input[@type=radio] 在新版會直接選不到元素。看到帶 @ 的舊範例,請一律改寫。

用陣列索引操作

// 讓第二個 radio 成為選中項
$('input[name=items]').get(1).checked = true;

完整實例

function getra(){
  var var_name = $("input[name='isspecialcnt']:checked").val();
  if (var_name == '1') {
    $("#isspecialcntyes").show();
    $("#isspecialcntno").hide();
  }
  if (var_name == '0') {
    $("#isspecialcntyes").hide();
    $("#isspecialcntno").show();
  }
}
<form name="form1" method="post" action="">
  <p>
    <label><input type="radio" name="radiogroup1" value="單選" id="radiogroup1_0"> 單選</label><br>
    <label><input type="radio" name="radiogroup1" value="單選" id="radiogroup1_1"> 單選</label><br>
    <label><input type="radio" name="radiogroup1" value="單選" id="radiogroup1_2"> 單選</label><br>
  </p>
</form>

更值得採用的現代寫法

.attr("checked", true) 在 jQuery 1.6 之後語意已經改變——attr 反映的是 HTML 初始狀態,控制當前狀態應該用 prop:

// 設定
$('input[name=items]').prop('checked', true);
// 或簡寫
$('input[name=items]').filter('[value="2"]').prop('checked', true);

// 取值
$('input[name=items]:checked').val();

若完全不需要 jQuery,原生寫法反而更短:

document.querySelector('input[name=items]:checked').value;

最後提醒,這個範例裡五個 radio 的 value 都寫成「單選」,實務上每個選項的 value 應該是唯一值,否則送出表單後無從分辨使用者選了哪一項。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved