asp:RadioButtonList 渲染為一組 <input type="radio">,每個選項的 value 對應 ListItem.Value,文字則在緊鄰的 <label> 或文字節點中。透過 jQuery 可輕鬆在客戶端即時取得使用者選取的值與顯示文字。
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Web.Default" %>
<!DOCTYPE html>
<html xmlns="https://www.w3.org/1999/xhtml">
<head runat="server">
<title>RadioButtonList jQuery 取值範例</title>
<script src="jquery-1.8.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
// 綁定 change 事件於 RadioButtonList 內所有 radio
$("#<%=rblHobbies.ClientID%> input[type=radio]").on("change", function () {
if (this.value !== "") {
// this.value 即 ListItem.Value
// $(this).next().text() 取得緊鄰的 label 文字(ListItem.Text)
$("#message").text("Text:" + $(this).next().text() + " Value:" + this.value);
}
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div style="margin: 100px auto; width: 400px; height: 200px;">
<fieldset style="width: 400px; height: 150px">
<p>請選擇興趣</p>
<asp:RadioButtonList ID="rblHobbies" runat="server">
<asp:ListItem Value="1">音樂</asp:ListItem>
<asp:ListItem Value="2">籃球</asp:ListItem>
<asp:ListItem Value="3">美劇</asp:ListItem>
<asp:ListItem Value="4">電影</asp:ListItem>
</asp:RadioButtonList>
</fieldset>
<br />
<div id="message" style="color: blue;"></div>
</div>
</form>
</body>
</html>
<span id="rblHobbies">
<input type="radio" name="rblHobbies" value="1" /><label>音樂</label>
<input type="radio" name="rblHobbies" value="2" /><label>籃球</label>
...
</span>
$("#<%=rblHobbies.ClientID%> input[type=radio]"):精準鎖定該控件內的所有單選鈕。$(this).next().text():取得緊鄰的 <label> 文字(即 ListItem.Text)。this.value:直接取得 value 屬性(即 ListItem.Value)。若需在 PostBack 時於後端取值,直接使用 rblHobbies.SelectedValue 或 rblHobbies.SelectedItem.Text。本文專注於「無 PostBack、純客戶端即時取值」情境,適合搭配 AJAX 或前端驗證使用。