Putting cursor at end of text field in javascript

I have a text box that when I set focus I want the cursor to move to the end of the text box.

A solution that continues to grow is simply

this.value = this.value

I tried this with a simple onclick method:

function InputClicked(element) {
    element.className = "inputfocused";
    element.value = element.value;
}

but strangely it seems to end with this, and then move on to the beginning of the text box.

+5
source share
3 answers

You need to focus the element and set the position of the carriage

This JSFiddle shows you how it works. jQuery was used for simplicity in this example, but it can be completely omitted if you so wish. A function is setSelectionRangein any case a DOM function.

In general, he does this:

input.focus();
input.setSelectionRange(inputValueLength, inputValueLength);

DOM ( jQuery).

?

, Chrome, , , . - :

input.setSelectionRange(1000,1000);

( 1000 .:)

. IE8 . . IE .

+7

selectionStart selectionEnd setSelectionRange() . IE < 9 , createTextRange() .

:

function moveCaretToEnd(el) {
    el.focus();
    if (typeof el.selectionStart == "number") {
        el.selectionStart = el.selectionEnd = el.value.length;
    } else if (typeof el.createTextRange != "undefined") {
        var range = el.createTextRange();
        range.collapse(false);
        range.select();
    }
}
+5

Simple and working 100%

1.Focus 2.Select a value 3.Empty It 4. Enter the value back

        $("#catg_name").focus();
        var value = $("#catg_name").val();
        $("#catg_name").val('');
        $("#catg_name").val(value);
+1
source

All Articles