在 ASP.NET 的表單中,RadioButtonList 與 RadioButton 是常見的單選控制項。當我們想在提交前確認使用者是否已做出選擇,就可以用 jQuery 來檢查。以下範例示範如何判斷它們是否有選中項,並讀取對應的值。
<%--Body 代碼--%> <div> <asp:RadioButtonList ID="RadioButtonList1" runat="server"> <asp:ListItem Value="A">a</asp:ListItem> <asp:ListItem Value="B">b</asp:ListItem> </asp:RadioButtonList> <asp:RadioButton ID="RadioButton1" GroupName="RBtn" Text="男" runat="server" Checked="true" /> <asp:RadioButton ID="RadioButton2" GroupName="RBtn" Text="女" runat="server" /> <asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="Button1_ClientClick()"></asp:Button> </div>
<%--Head 代碼--%>
<script language="javascript" type="text/javascript" src="js/jquery-1.9.1.js"></script>
<script language="javascript" type="text/javascript">
function Button1_ClientClick()
{
alert($("input[name='RadioButtonList1']:checked").val()); // 若都沒有選中,彈出 "undefined",若有選中則彈出對應 Value
if(document.getElementById("RadioButton1").checked == true) // 若 RadioButton1 被選中
{
alert($("#RadioButton1:checked").val()); // 彈出 RadioButton1 的值
alert($("#RadioButton2:checked").val()); // 彈出 undefined(因為它沒被選中)
alert($("#RadioButton1:checked").val() == "RadioButton1"); // 彈出 true
}
return false; // 暫時不傳到後台
}
</script>
判斷的核心在於 :checked 偽類。對 RadioButtonList 而言,它會渲染成一組同名(name 為控制項 ID)的 radio,因此用 $("input[name='RadioButtonList1']:checked").val() 就能取到選中項的值;若無任何選項被勾選,val() 會回傳 undefined。對於獨立的 RadioButton,則可用 $("#RadioButton1:checked").val() 逐一檢查。掌握這個模式,表單提交前的「必選」驗證便能輕鬆完成。