Home > Web Front-end > JS Tutorial > body text

How to Insert Text at the Cursor Position in a Text Area using JavaScript?

Patricia Arquette
Release: 2024-11-20 11:32:02
Original
923 people have browsed it

How to Insert Text at the Cursor Position in a Text Area using JavaScript?

Inserting Text at Cursor Position with Javascript/jQuery

In web development, adding text where the cursor is positioned can enhance user experience. One scenario includes allowing users to seamlessly insert predefined text into a textbox upon clicking a link.

Inserting Text at Cursor Position

To insert text at the cursor position, we can utilize the following JavaScript function:

function insertAtCaret(areaId, text) {
  // Get the textarea element
  var txtarea = document.getElementById(areaId);

  // Check if the element exists
  if (!txtarea) {
    return;
  }

  // Determine the browser type (Internet Explorer or others)
  var br = ((txtarea.selectionStart || txtarea.selectionStart == '0') ?
    "ff" : (document.selection ? "ie" : false));

  // Calculate the cursor position
  var strPos = 0;
  if (br == "ie") {
    txtarea.focus();
    var range = document.selection.createRange();
    range.moveStart('character', -txtarea.value.length);
    strPos = range.text.length;
  } else if (br == "ff") {
    strPos = txtarea.selectionStart;
  }

  // Create a string that consists of the text before, after, and the inserted text
  var front = (txtarea.value).substring(0, strPos);
  var back = (txtarea.value).substring(strPos, txtarea.value.length);
  txtarea.value = front + text + back;

  // Reset the cursor position after inserting the text
  strPos = strPos + text.length;
  if (br == "ie") {
    txtarea.focus();
    var ieRange = document.selection.createRange();
    ieRange.moveStart('character', -txtarea.value.length);
    ieRange.moveStart('character', strPos);
    ieRange.moveEnd('character', 0);
    ieRange.select();
  } else if (br == "ff") {
    txtarea.selectionStart = strPos;
    txtarea.selectionEnd = strPos;
    txtarea.focus();
  }
}
Copy after login

Example Usage

The following HTML and JavaScript code demonstrates how to use the insertAtCaret() function:

<textarea>
Copy after login

The above is the detailed content of How to Insert Text at the Cursor Position in a Text Area using JavaScript?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template