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

ASP.NET 使用 jQuery 取得 RadioButtonList 選取項目的文字與值

     編輯:ASP.NET 基礎

情境說明

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>

關鍵選取器與 DOM 結構

<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 或前端驗證使用。

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