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
DDDOriginal
2024-12-12 13:23:10387browse

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;

Quirkier Browsers' Solution

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

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

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);
});

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!

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