warang
warang

Reputation: 43

How to set focus at the end of textbox while typing?

I have a textbox with a live search function. It is working all good except one problem. If I type any characters on it, it just loses its focus. If I set textbox.Focus(), the cursor goes at the beginning of the textbox.

I have tried most of solutions on the internet. Please check my codes below.

asp:TextBox ID="searchCompany" runat="server" Text="" CssClass="searchCompany" AutoPostBack="true" Width="190px" OnTextChanged="searchCompany_TextChanged"></asp:TextBox>

In page_Load

protected void Page_Load(object sender, EventArgs e)
        {

            //ScriptManager1.RegisterAsyncPostBackControl(Menu1);
            menuDisplay();
            searchCompany.Attributes.Add("onkeyup", "setTimeout('__doPostBack(\\'" + searchCompany.UniqueID + "\\',\\'\\')', 0);");

            //searchCompany.Attributes.Add("onfocus", "javascript:setSelectionRange('" + "','')");
            //searchCompany.Focus();


        }

and I have tried javascript as below

<script type="text/javascript">

    function setSelectionRange() {
        var inputField = document.getElementById('searchCompany');
        if (inputField != null && inputField.value.length > 0) {
            if (inputField.createTextRange) {
                var FieldRange = inputField.createTextRange();
                FieldRange.moveStart('character',inputField.value.length);
                FieldRange.collapse();
                FieldRange.select();
            }
        }
    }

</script>

I have tried to put codes on a method "searchCompany_TextChanged" which is calling if user type any characters on a textbox everytime however it is not working as well.

I saw other solutions with using Textbox.Select() but System.Windows.Control is not working in asp.net i guess.

Any idea??

Upvotes: 0

Views: 3690

Answers (1)

lmortenson
lmortenson

Reputation: 1605

There's a very simple trick that's worked for me. Basically, set the text value of the of input to itself to its own text value, and that will move the cursor to the end of the text. Then just focus it. This code uses jQuery to demonstrate that, but you should be able to do that in straight JS as well.

HTML

<input type="text" id="focusText"></input>
<button id="focusButton">Set Focus</button>

JavaScript

$("#focusButton").click(function()  {
    var text = $("#focusText").val();
    $("#focusText").val(text).focus();
})

Here's a non jQuery example of the JavaScript, HTML should be the same:

document.getElementById("focusButton").onclick = function()  {
    var inputElement = document.getElementById("focusText");
    var text = inputElement.value;
    inputElement.value = text;
    inputElement.focus();
}

Here's a fiddle demonstrating the non-jQuery version of the code: http://jsfiddle.net/C3gCa/

Upvotes: 2

Related Questions