【问题标题】:ASP.Net RadioButtonList: using jQuery to get the ListItem selectedASP.Net RadioButtonList:使用 jQuery 获取选中的 ListItem
【发布时间】:2012-03-13 07:00:08
【问题描述】:

有 2 个 RadioButtonLists:

Are you a minor?:  oYes  oNo
Do you wish a joint account?:  oYes  oNo

如果第一个问题的答案是肯定的,我想检测对第一个问题的回答,并使用 jQuery 函数将第二个问题的答案设置为是。提前致谢。

<asp:Label ID="lblMinfor" CssClass="boldIt" runat="server" Text="Is this account for a minor" Style="float: left; width: 200px;"></asp:Label><br />
<asp:RadioButtonList ID="rdlMinor" runat="server" RepeatDirection="Horizontal" Width="130px" Style="float: left;" BorderStyle="None" RepeatLayout="Flow" ()>
    <asp:ListItem>Yes</asp:ListItem>
    <asp:ListItem Selected="True">No</asp:ListItem>
</asp:RadioButtonList>
<asp:Label ID="lblJoint" CssClass="boldIt" runat="server" Text="Is this for a joint account?" Style="float: left; width: 200px;"></asp:Label><br />
<asp:RadioButtonList ID="rdlJoint" runat="server" RepeatDirection="Horizontal" Width="130px" Style="float: left;" BorderStyle="None" RepeatLayout="Flow">
    <asp:ListItem>Yes</asp:ListItem>
    <asp:ListItem Selected="True">No</asp:ListItem>
</asp:RadioButtonList>

【问题讨论】:

  • 你能发布按钮的 HTML 吗?

标签: c# jquery asp.net selecteditem radiobuttonlist


【解决方案1】:
$('#<%=rdlMinor.ClientID %>').change(function() {
    if($('#<%=rdlMinor.ClientID %> input:checked').val() == 'Yes') 
    {
        $('#<%=rdlJoint.ClientID %>').find("input[value='Yes']").attr("checked", "checked");
    }
});

【讨论】:

  • 当 ASP.Net 呈现为 HTML 时,ID 发生了变化,不再是 'rdlMinor;'它是动态创建的。当 jQuery 脚本加载到内存中时,该 ID 不可用,因此无法在 jQuery 中访问。
  • 您可以在控件上使用 ClientIDMode="Static" 来保留标记中定义的 ID。
【解决方案2】:

试试这个代码:

<script type="text/javascript">

$(document).ready(function() {

    $("#<%=rdlMinor.ClientID%>").change(function()
    {
        var rbvalue = $("input[@name=<%=rdlMinor.ClientID%>]:radio:checked").val();

        if(rbvalue == "Yes")
        {
            $('#<%=rdlJoint.ClientID %>').find("input[value='Yes']").attr("checked", "checked");
        }
    });

});

</script>

更多关于这些主题:

JQuery Accessing the Client Generated ID of ASP.NET Controls

How to Set Get RadioButtonList Selected Value using jQuery

【讨论】:

  • 当 ASP.Net 呈现为 HTML 时,ID 发生了变化,不再是 'rdlMinor;'它是动态创建的。当 jQuery 脚本加载到内存中时,该 ID 不可用,因此无法在 jQuery 中访问。
  • 这就是我们使用$("#&lt;%=rdlMinor.ClientID%&gt;") 而不仅仅是$(#rdlMinor") 的原因。这第一个构造将在 jQuery 代码中放置 ASP.NET 用于该控件的确切 ID。确实是动态的。这就是为什么我们需要使用$("#&lt;%=rdlMinor.ClientID%&gt;")。顺便说一句,您应该在页面加载完成后将您的 jQuery 代码放入 jQuery 就绪事件中。我会更新代码。
  • 我刚刚更正了我之前代码中的一个错字,我用&lt;%=dlMinor.ClientID%&gt; 而不是&lt;%=rdlMinor.ClientID%&gt;。看看上面更正的代码现在是否有效并返回......
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-11-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多