如何选择TextBox时如何选择单选按钮?

时间:2012-02-16 20:23:52

标签: asp.net

TextBox旁边有RadioButton,当有人选择TextBox时,应将关联的RadioButton设为已选中。

我使用此代码,直到我发现它只适用于Chrome:

<asp:RadioButton runat="server" GroupName="SomeGroup" ID="rbOption3" />
<asp:Label runat="server" AssociatedControlID="rbOption3">
    <asp:Label runat="server" Text="Pay other amount" />
    <asp:TextBox runat="server" ID="txtOtherAmount" CssClass="money-text" />
    <div class="align-with-radiobutton small-text">
        The minimum amount for web payments is <asp:Label runat="server" ID="lblMinPayment" />. If you are looking to pay a lower
        amount, please <a href="Contact.aspx">contact us</a> and speak with a representative.
    </div>
</asp:Label>

enter image description here

它在所有3个主流浏览器中表现不同

IE:选择TextBox时,选择根本不会改变

FireFox: MouseUp上的选择更改,这意味着无论何时选择TextBox,焦点都会更改为RadioButton,这使得TextBox看起来不可选

Chrome:MouseDown

选择更改以来工作正常

我的要求是用户可以选择Text或TextBox的任何部分,然后选择单选按钮。

如果TextBox通过鼠标或键盘导航获得焦点,如何选择关联的RadioButton?

修改

rsbarro发布的解决方案适用于IE和Chrome,但FireFox仍然失败。当您在FireFox中选择TextBox时,RadioButton会将注意力集中在MouseUp上,这使得它看起来无法选择TextBox。

我尝试使用一些jQuery,但是.changed().focus()在选择TextBox时不会被触发(虽然它们在选择Label时会被触发),我似乎无法停止事件。

2 个答案:

答案 0 :(得分:1)

以下方法适用于最新版本的IE,Firefox和Chrome:

<script type="text/javascript">
    function selectRadio3() {
        var rb = document.getElementById('<%= rbOption3.ClientID %>');
        rb.checked = true;
    }

    function selectOtherAmount() {
        var txt = document.getElementById('<%= txtOtherAmount.ClientID %>');
        txt.focus();
    }
</script>

<asp:RadioButton runat="server" GroupName="SomeGroup" ID="rbOption3" onclick="javascript:selectOtherAmount()" />
<asp:Label ID="Label1" runat="server" AssociatedControlID="txtOtherAmount" Text="Pay other amount" />
<asp:TextBox runat="server" ID="txtOtherAmount" onfocus="javascript:selectRadio3()" CssClass="money-text" />
<div class="align-with-radiobutton small-text" onclick="javascript:selectOtherAmount()">
    The minimum amount for web payments is <asp:Label runat="server" ID="lblMinPayment" />. If you are looking to pay a lower
    amount, please <a href="Contact.aspx">contact us</a> and speak with a representative.
</div>

我将LabelTextBox相关联,并在checked获得焦点时添加了javascript以设置RadioButton的{​​{1}}属性。我还在TextBox上添加了onclick个事件,将焦点设置为RadioButton

修改
使用原始HTML并添加一些javascript也适合我。我向TextBox添加了onclick个事件,以便将焦点设置为RadioButton,并在TextBox上设置onfocus个事件以设置TextBox } checked的属性。

RadioButton

答案 1 :(得分:0)

rsbarro的回答是正确的。

但是,如果你正在使用jquery,那么它是如何做到的: http://jsfiddle.net/vg8gU/3/

jquery的优势在于您不必担心不同的浏览器。它“适用于所有浏览器。”