Place Cursor at End of Text Input Element in JavaScript
Placing the cursor at the end of a text input element through JavaScript is a straightforward task, especially after focus is set to the element. Let's explore the most efficient and straightforward approach:
The following code snippet provides a simple yet effective solution:
this.selectionStart = this.selectionEnd = this.value.length;
This line calculates the length of the input value and sets both the start and end cursors to that position. This method works in most major browsers.
However, certain browsers exhibit quirks that necessitate a more comprehensive solution:
setTimeout(function(){ that.selectionStart = that.selectionEnd = 10000; }, 0);
In this code snippet, a setTimeout() is utilized to address potential browser inconsistencies. It sets the cursor position to an arbitrarily large number (e.g., 10000), ensuring that it is beyond the end of the input text, essentially placing it at the end.
Additionally, you can utilize jQuery to set the focus listener:
$('#el').focus(function(){ var that = this; setTimeout(function(){ that.selectionStart = that.selectionEnd = 10000; }, 0); });
The above is the detailed content of How to Reliably Place the Cursor at the End of a Text Input Element in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!