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
Release: 2024-11-30 04:31:11
Original
911 people have browsed it

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;
Copy after login

However, to account for browser inconsistencies, a more comprehensive solution is:

setTimeout(function(){ that.selectionStart = that.selectionEnd = 10000; }, 0);
Copy after login

When using jQuery, you can set a listener:

$('#el').focus(function(){
  var that = this;
  setTimeout(function(){ that.selectionStart = that.selectionEnd = 10000; }, 0);
});
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template