Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Putting cursor at end of textbox in javascript

I have a textbox that when I put on focus I want the cursor to goto the end of the textbox.

The solution that keeps coming up is just

this.value = this.value

I have tried this with a simple method onclick:

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

but the strange this with this, it seems to goto the end and then jump to the start of the textbox.

like image 917
Michael Avatar asked Aug 08 '12 08:08

Michael


People also ask

What is setSelectionRange in JavaScript?

setSelectionRange() method sets the start and end positions of the current text selection in an <input> or <textarea> element. Optionally, in newer browser versions, you can specify the direction in which selection should be considered to have occurred.

How do you set focus on input field?

To set focus to an HTML form element, the focus() method of JavaScript can be used. To do so, call this method on an object of the element that is to be focused, as shown in the example. Example 1: The focus() method is set to the input tag when user clicks on Focus button.

How can input focus in jQuery?

Using jQuery With jQuery, you can use the . focus() method to trigger the “focus” JavaScript event on an element. This method is a shortcut for . trigger("focus") method.


1 Answers

You have to focus element AND set caret position

This JSFiddle shows you how it works. jQuery has been used for simplicity in this example, but it can be completely omitted if one desires so. setSelectionRange function is a DOM function anyway.

In general it does this:

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

Obtaining input and its value length can be obtained using DOM functionality or using library functions (as in jQuery).

Do we need input value length?

I haven't tested in other browsers but running in Chrome it allows to set a larger than actual position and caret will be positioned at the end. So something like:

input.setSelectionRange(1000,1000);

will work as expected (provided your text is shorter than 1000 characters. :)

Note: This function isn't supported in IE8 and older. All latest versions of most used browsers support it. For older versions of IE resort to text ranges.

like image 107
Robert Koritnik Avatar answered Oct 29 '22 01:10

Robert Koritnik