R
R
Roman2014-10-20 14:16:15
JavaScript
Roman, 2014-10-20 14:16:15

Why does selection disappear in input after element.select()?

Hello!
Faced with the need to highlight the value in the text field on focus.
I wrote a simple directive for this:

function inputFocusDirective() {
    return {
        restrict: "A",
        link: function (scope, element, attrs) {
            element.on("focus", function () {
                scope.$apply(function() {
                    element.select();
                });
            });
         }
    }
}

Everything would be fine, but the following happens:
during the "focus" event, the value in the field is selected, then the selection disappears and the cursor moves to the first position of the value that was in the field at that moment.
At first I thought that it was the tricks of BootStrap v3.2.0 - disabled, did not help
Then that JQuery (version 1.11.1) - similar
Then that AngularJs (v1.2.26)

In the end, I wrote the simplest (in my opinion) opinion option : The result is the same - during the "focus" event, the value in the field is selected, then the selection disappears and the cursor moves to the first position of the value that was in the field at that moment.
<input type="text" onfocus="this.select()">

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Sydorenko, 2014-10-20
@uaKorona

Try this solution

<input onClick="this.setSelectionRange(0, this.value.length)" value="Sample Text" />

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question