2020年6月8日 星期一

ASP.NET WebForm RadioButtonList 使用JQuery取得使用者所選擇的項目

參考資料1:[jQuery] RadioButtonList 取值


<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
    <script src="js/jquery-1.11.3.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $('input[type="radio"][name="<%=RBL1.UniqueID %>"]').change(function () {
                var SelectVal = $(this).val();
                var SelectText = $(this).closest('td').find('label').text(); //用closest取得radio上一層的td,並取得label的text
                $('#<%=Label1.ClientID%>').text(SelectText+':');

            });
//法1.請看參考資料1
            //$('#<%=Label1.ClientID%>').text($('input:radio[name="<%=RBL1.UniqueID %>"]:checked + label').text()+':');
//法2.先取得RadioButtonList預設選取哪一個項目,並用closest取得radio上一層的td,並取得label的text
            $('#<%=Label1.ClientID%>').text($('input:radio[name="<%=RBL1.UniqueID %>"]:checked').closest('td').find('label').text()+':');
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <div>
    查詢方式:
            <asp:RadioButtonList ID="RBL1" runat="server" RepeatDirection="Horizontal">
                <asp:ListItem Selected="True" Value="0">姓名</asp:ListItem>
                <asp:ListItem Value="1">學號</asp:ListItem>
            </asp:RadioButtonList>
            <br/>
            <asp:Label ID="Label1" runat="server"></asp:Label>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        </div>
    </form>
</body>
</html>