本文整理 jQuery 操作 radio 單選組時,取得與設定選中值的常用語法。
取得選中項的值:
$("input[@type=radio][@checked]").val();
設定 value=2 的項目為當前選中項:
$("input[@type=radio]").attr("checked",'2');
取得一組 radio 被選中項的值:
var item = $('input[@name=items][@checked]').val();
讓 radio 單選組的第二個元素為當前選中值:
$('input[@name=items]').get(1).checked = true
寫法同樣隨版本而異:
jQuery 舊版本:
var_name = $("input[@name='radio_name']:checked").val();
jQuery 1.3 以後版本:
var_name = $("input[name='radio_name']:checked").val();
function getra(){ var_name = $("input[name='isspecialcnt']:checked").val(); //alert(var_name); 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> </p> </form>
掌握 :checked 選取加上 val() 取值,就能輕鬆讀取單選組目前的選擇狀態。