Home >Web Front-end >JS Tutorial >How Can I Set the Cursor Position in a jQuery Text Area?
Challenge:
Need a method to set the cursor position in a text area using jQuery. The desired behavior is to position the cursor at a specific offset when the field is focused.
jQuery Solution:
$.fn.setCursorPosition = function(pos) { if (this.setSelectionRange) { this.setSelectionRange(pos, pos); } else if (this.createTextRange) { var range = this.createTextRange(); range.collapse(true); if (pos < 0) { pos = $(this).val().length + pos; } range.moveEnd("character", pos); range.moveStart("character", pos); range.select(); } };
Usage:
$('#input').focus(function() { $(this).setCursorPosition(4); });
This would position the cursor after the fourth character in the text field.
Alternative Solution:
$.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(); } }); };
This allows for more versatile text selection, including selecting a range of characters:
$('#elem').selectRange(3, 5); // select a range of text $('#elem').selectRange(3); // set cursor position
The above is the detailed content of How Can I Set the Cursor Position in a jQuery Text Area?. For more information, please follow other related articles on the PHP Chinese website!