Question:
How can you conveniently place the cursor at the end of the text within an input text element using JavaScript after focusing on that element?
Answer:
A straightforward approach works in most browsers:
this.selectionStart = this.selectionEnd = this.value.length;
However, to account for browser inconsistencies, a more comprehensive solution is:
setTimeout(function(){ that.selectionStart = that.selectionEnd = 10000; }, 0);
When using jQuery, you can set a listener:
$('#el').focus(function(){ var that = this; setTimeout(function(){ that.selectionStart = that.selectionEnd = 10000; }, 0); });
The above is the detailed content of How to Position the Cursor at the End of an Input Field using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!