Home >Web Front-end >JS Tutorial >How Can I Set the Cursor Position in a Text Area Using jQuery?
Problem:
How can you set the cursor position within a text area using jQuery? You have a text area with existing content, and you want to automatically position the cursor at a specific offset when the field receives focus.
Solution:
For jQuery, the following code snippet can be used to achieve this functionality:
$.fn.selectRange = function(start, end) { if(end === undefined) { end = start; } return this.each(function() { if('selectionStart' in this) { this.selectionStart = start; this.selectionEnd = end; } else if(this.setSelectionRange) { this.setSelectionRange(start, end); } else if(this.createTextRange) { var range = this.createTextRange(); range.collapse(true); range.moveEnd('character', end); range.moveStart('character', start); range.select(); } }); };
With this function, you can use the following syntax:
$('#elem').selectRange(3,5); // select a range of text $('#elem').selectRange(3); // set cursor position
This allows you to set the cursor position within the text area, whether you want to select a range of text or simply position the cursor at a specific offset.
Additional Resources:
The above is the detailed content of How Can I Set the Cursor Position in a Text Area Using jQuery?. For more information, please follow other related articles on the PHP Chinese website!