首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> 關於ASP.NET

jQuery 獲取 ASP.NET RadioButtonList 選中項文字與值的方法

     編輯:關於ASP.NET

<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>

核心選取器與 DOM 結構

<!-- 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。

常見變體與注意事項

  • RepeatLayout="Table" (預設):渲染為 <table><tr><td><input><label></td></tr>...</table>,$(this).next() 仍有效 (label 緊隨 input)。
  • RepeatLayout="Flow":渲染為 <span><input><label></span>,同樣適用。
  • RepeatDirection="Vertical":不影響選取器。
  • 獲取後端選中值:PostBack 時直接用 rblHobbies.SelectedValue / SelectedItem.Text,無需 JS。
  • 動態綁定:若項目經 AJAX 動態載入,改用事件委派 $(document).on('change', '#rblHobbies input[type=radio]', fn)。

此技巧同樣適用於 CheckBoxList (多選),只需將選取器改為 input[type=checkbox] 並迭代 :checked 項目。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved