asp:RadioButtonList 渲染為一組 <input type="radio">,搭配 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"></script>
<script>
$(function () {
// 綁定 change 事件
$('#<%=rblHobbies.ClientID%> input[type=radio]').on('change', function () {
if (this.value !== '') {
// $(this).next() 取得緊鄰的 label 文字
$('#message').text('Text:' + $(this).next().text() + ' Value:' + this.value);
}
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div style="margin:100px auto; width:400px;">
<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>
$('#<%=rblHobbies.ClientID%> input[type=radio]')
ClientID 確保抓到正確的渲染 ID (如 ctl00_ContentPlaceHolder1_rblHobbies)。input[type=radio] 只選取單選按鈕本身。this.value 或 $(this).val()。<label>,故 $(this).next().text() 即可取得顯示文字。// 後端 C#
string selectedValue = rblHobbies.SelectedValue; // "1" ~ "4"
string selectedText = rblHobbies.SelectedItem.Text; // "音樂" 等