Home > Web Front-end > JS Tutorial > How Can I Set the Cursor Position in a jQuery Text Area?

How Can I Set the Cursor Position in a jQuery Text Area?

DDD
Release: 2024-12-28 05:55:13
Original
190 people have browsed it

How Can I Set the Cursor Position in a jQuery Text Area?

jQuery Set Cursor Position in 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();
  }
};
Copy after login

Usage:

$('#input').focus(function() {
  $(this).setCursorPosition(4);
});
Copy after login

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();
    }
  });
};
Copy after login

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
Copy after login

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!

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