Home >Web Front-end >JS Tutorial >How to Set the Cursor Position or Select Text in a Text Area Using jQuery?

How to Set the Cursor Position or Select Text in a Text Area Using jQuery?

Barbara Streisand
Barbara StreisandOriginal
2024-12-15 13:35:14856browse

How to Set the Cursor Position or Select Text in a Text Area Using jQuery?

How to Set the Cursor Position in a Text Area Using jQuery

The $.fn.selectRange() function allows you to easily set the cursor position or select a range of text in a text area using jQuery.

Here's how you can use it:

$.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 set the cursor position by providing a single argument, like so:

$('#elem').selectRange(3); // set cursor position

Or, you can select a range of text by providing two arguments:

$('#elem').selectRange(3,5); // select a range of text

This function works by checking if the selectionStart and selectionEnd properties are supported by the browser. If they are, it uses those to set the cursor position or selection range. Otherwise, it uses the setSelectionRange() method, which is supported by most browsers. Finally, if neither of those methods are available, the function falls back to using the createTextRange() method, which is available in Internet Explorer.

Here are some handy examples of how to use this function:

  • Select all text in a text area:
$('#elem').selectRange(0, $('#elem').val().length);
  • Set the cursor to the end of the text in a text area:
$('#elem').selectRange($('#elem').val().length);
  • Select a specific range of text in a text area:
$('#elem').selectRange(3, 7);

You can find live demos of this function on JsFiddle and JsBin.

The above is the detailed content of How to Set the Cursor Position or Select Text in a Text Area Using jQuery?. 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