JohnyMoraes
JohnyMoraes

Reputation: 165

C# WebForm - Set focus of textbox with Javascript

I have a Javascript that when i write in one textbox, it fills another textbox. But i need that the focus stay in a third textbox.

Actually, my code is:

<script type="text/javascript" language="javascript">
        function SelectValue(source, eventArgs) {
            document.getElementById('<%= txtCodeProduct.ClientID %>').value = eventArgs.get_value();
            document.getElementById('<%= txtQuantity.ClientID %>').focus();
            }
</script>

but the focus don't work...If i put an alert in a code, the focus work:

<script type="text/javascript" language="javascript">
        function SelectValue(source, eventArgs) {
            document.getElementById('<%= txtCodeProduct.ClientID %>').value = eventArgs.get_value();
            document.getElementById('<%= txtQuantity.ClientID %>').focus();
            alert("test");
            }

How i resolve this without use alert ? My textbox are in a form that uses update panel.

Thanks.

Upvotes: 1

Views: 4056

Answers (2)

JP Hellemons
JP Hellemons

Reputation: 6047

What version of Asp.Net do you use? otherwise you can use ClientIDMode http://msdn.microsoft.com/en-us/library/system.web.ui.control.clientidmode.aspx

<asp:TextBox ID="txtCodeProduct" runat="server" ClientIDMode="static" />
<asp:TextBox ID="txtQuantity"    runat="server" ClientIDMode="static" />

I also recommend using jQuery:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" ></script>
<script type="text/javascript">
    function SelectValue(source, eventArgs) {
        $("#txtCodeProduct").val(eventArgs.get_value());
        $("#txtQuantity").focus();
    }

http://api.jquery.com/focus/

Upvotes: 1

Akhil Sekharan
Akhil Sekharan

Reputation: 12683

Try:

 function SelectValue(source, eventArgs) {
    document.getElementById('<%= txtCodeProduct.ClientID %>').value = eventArgs.get_value();
    setTimeout( function(){
            document.getElementById('<%= txtQuantity.ClientID %>').focus();
        }, 0);
}

Upvotes: 1

Related Questions