Home > Web Front-end > JS Tutorial > How Can I Place the Cursor at the End of Text in a JavaScript Input Field?

How Can I Place the Cursor at the End of Text in a JavaScript Input Field?

DDD
Release: 2024-12-12 13:23:10
Original
376 people have browsed it

How Can I Place the Cursor at the End of Text in a JavaScript Input Field?

Locating the Cursor to the End of Text in an Input Element Using JavaScript

When focus is set to a text input element, it's often desirable to position the cursor at the end of the existing text. Achieving this requires JavaScript intervention.

Most Browsers' Solution

For most browsers, a straightforward approach suffices:

this.selectionStart = this.selectionEnd = this.value.length;
Copy after login

Quirkier Browsers' Solution

However, certain browsers present quirks that necessitate a more comprehensive approach:

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

Utilizing jQuery (Optional)

jQuery can be employed to establish the event listener, as demonstrated below:

$('#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 Can I Place the Cursor at the End of Text in a JavaScript Input Field?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template