Home >Web Front-end >JS Tutorial >How to Position the Cursor at the End of an Input Field using JavaScript?

How to Position the Cursor at the End of an Input Field using JavaScript?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-30 04:31:11919browse

How to Position the Cursor at the End of an Input Field using JavaScript?

JavaScript: Positioning Cursor at Text End in Input Field

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn