<asp:RadioButtonList> 渲染為一組 <input type="radio">,搭配 <label>。本文示範使用 jQuery 綁定 change 事件,精準取得使用者選中的項目 Value (值) 與 Text (顯示文字)。
<%@ 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">
$(document).ready(function () {
// 選取 RadioButtonList 內所有 radio input
$("#<%=rblHobbies.ClientID%> input[type=radio]").on("change", function () {
if (this.value !== "") {
// $(this).next() 取得緊鄰的 label 元素 (即文字)
var text = $(this).next().text();
var value = this.value;
$("#message").text("Text:" + text + " Value:" + 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>
<!-- RadioButtonList 渲染後的 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():取得緊鄰的 <label> 元素 (ASP.NET 預設渲染),.text() 即為顯示文字。this.value:原生 DOM 屬性,即 ListItem.Value。<table><tr><td><input><label></td></tr>...</table>,$(this).next() 仍有效 (label 緊隨 input)。<span><input><label></span>,同樣適用。rblHobbies.SelectedValue / SelectedItem.Text,無需 JS。$(document).on('change', '#rblHobbies input[type=radio]', fn)。此技巧同樣適用於 CheckBoxList (多選),只需將選取器改為 input[type=checkbox] 並迭代 :checked 項目。