萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> ASP.NET 程式設計

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

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()。
  • 文字:RadioButtonList 渲染時,每個 radio 後緊接一個 <label>,故 $(this).next().text() 即可取得顯示文字。

補充:取得後端選取值

// 後端 C#
string selectedValue = rblHobbies.SelectedValue; // "1" ~ "4"
string selectedText  = rblHobbies.SelectedItem.Text; // "音樂" 等
copyright © 萬盛學電腦網 all rights reserved