Home >Web Front-end >JS Tutorial >How Do I Programmatically Place the Cursor at the End of a Text Input in JavaScript?
Placing the Cursor at the End of Text Input with JavaScript
Placing the cursor at the end of a text input element is a common task in web development. While setting focus to the element is straightforward, getting the cursor to the end of the entered text can be tricky.
JavaScript Solution
The simplest approach in most browsers is to set both the selectionStart and selectionEnd properties of the input element to the length of its value:
this.selectionStart = this.selectionEnd = this.value.length;
Inclusive Solution for Quirky Browsers
However, some browsers exhibit quirks that require a more inclusive approach:
setTimeout(function(){ that.selectionStart = that.selectionEnd = 10000; }, 0);
This solution sets a very large value to selectionStart and selectionEnd to ensure that the cursor is placed at the far end of the text.
Using jQuery
While not strictly necessary, you can use jQuery to set the event listener:
$('#el').focus(function(){ var that = this; setTimeout(function(){ that.selectionStart = that.selectionEnd = 10000; }, 0); });
The above is the detailed content of How Do I Programmatically Place the Cursor at the End of a Text Input in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!