Alan Fisher
Alan Fisher

Reputation: 2055

How do I place the cursor at the end of the string in a text box when it gets focus?

I have an input text box that is data bound to an mvvm value which I default string of "RFQ". When the user tabs into the textbox I want the cursor to be at the end of the string. Current behavior has the string highlighted. I downloaded a jQuery library (jquery-caret.js) which has a method called .caretToEnd() and it works very well if I use it in the Document Ready like this:

 $("#txtRfq").caretToEnd();  

But I want to use it like this:

$("#txtRfq").focus(function () {
     $("#txtRfq").caretToEnd();
    });

But when I tab into the text box with this code loaded the entire string "RFQ" is highlighted. What am I missing here?

Upvotes: 1

Views: 1449

Answers (1)

Harry
Harry

Reputation: 89780

The native focus action (highlighting of text) cannot be suppressed and hence we have to add a delay and then call the caretToEnd() function like shown below.

    $("#txtRfq").on("focus", function (e) {
        $(this).delay(13).caretToEnd();
    });

This link has a working sample.

The above information is based on the example provided here

Upvotes: 2

Related Questions