Inserting text at cursor in a textarea, with Javascript

Active3 hr before
Viewed126 times

8 Answers


1 Comment on How to Insert Text into the Text Area at the Current Cursor Position? ,In this article, we’ll look at how to insert text into the text area at the current cursor position.,Sometimes, we want to insert text into a text area at the current cursor position.,We can insert text into an input at the cursor position when we press a key with the setRangeText method.

For instance, if we have the following input:

<input id="input" />
load more v

For the sake of proper Javascript,Use selectionStart/selectionEnd properties of the input element (works for <textarea> as well), 1 possible duplicate of Inserting a text where cursor is using Javascript/jquery – user Jul 26 '15 at 5:48 ,Credit to for the triggerEvent function

Use selectionStart/selectionEnd properties of the input element (works for <textarea> as well)

function insertAtCursor(myField, myValue) {
   //IE support
   if (document.selection) {
      sel = document.selection.createRange();
      sel.text = myValue;
   //MOZILLA and others
   else if (myField.selectionStart || myField.selectionStart == '0') {
      var startPos = myField.selectionStart;
      var endPos = myField.selectionEnd;
      myField.value = myField.value.substring(0, startPos) +
         myValue +
         myField.value.substring(endPos, myField.value.length);
   } else {
      myField.value += myValue;
load more v

How to insert text into the textarea at the current cursor position?,First, get the current position of cursor with the help of property named as selectionStart on textarea/inputbox.,To insert text into the textarea/inputbox at the current cursor position we need to get the current position of the cursor. So here the approach to get the current position of the cursor.,this line gives us the current position/start position of the cursor. 


// will give the current position of the cursor

// will get the value of the text area
let x = $('#text1').val();

// will get the value of the input box
let text_to_insert = $('#insert').val();

// setting the updated value in the text area
$('#text1').val(x.slice(0, curPos) + text_to_insert + x.slice(curPos));


load more v

While working on another project, I needed a way to insert some text at the current cursor position in a textarea to auto-complete what user is typing. It turns out this simple task is almost impossible to achieve if you want the browser to not choke on a big text inside a textarea.,The code did error out if I tried to insert on pretty much any other position than 0, but it got me curious.,It’s great to see the web platform grow and get features like Service Workers, but one of the areas that traditionally gets little to no attention is dealing with user input.,Of course, as I stumbled onto this problem, I reached out to a trusty search engine pointing me towards ever-prevailing StackOverflow and a couple of answers there (1, 2).

If you ignore old IEs, proposed solution in modern browsers boils down to roughly this:

function insertAtCursor(input, textToInsert) {
   // get current text of the input
   const value = input.value;

   // save selection start and end position
   const start = input.selectionStart;
   const end = input.selectionEnd;

   // update the value with our text inserted
   input.value = value.slice(0, start) + textToInsert + value.slice(end);

   // update cursor to be at the end of insertion
   input.selectionStart = input.selectionEnd = start + textToInsert.length;
load more v

What is 'CodeProject'?,View Unanswered Questions,This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL), Import GitHub Project


This library provides a consistent (and fast!) way to insert some text at the cursor position into a textrea or a text input field. If the field contains a selection, the selected text will be replaced with a given one.,All previously existing solution that I could find rely on getting full value of the the textarea, then slicing in necessary text, resetting new value and then restoring selection to the right position.,Due to the nature of the APIs used, the library will always focus the target field and set the cursor after the inserted text.,

npm install--save insert - text - at - cursor
load more v

Means when I click on a button its value should be inserted to the text area where cursor exists.,I have 4 text boxes and a button, I want when I click the button, it should Insert a value in the textbox where cursor exists.,from then on, window.lstText automatically refers to the current textarea.,I need some modification in the below code:

  1. I want to do the things without using form (if possible)
  2. I want both the buttons should work for any of the textarea.
<script type="text/javascript">
function insert(el,ins) {
    if (el.setSelectionRange){
        el.value = el.value.substring(0,el.selectionStart) + ins + el.value.substring(el.selectionStart,el.selectionEnd) + el.value.substring(el.selectionEnd,el.value.length);
    else if (document.selection && document.selection.createRange) {
        var range = document.selection.createRange();
        range.text = ins + range.text;

<input type="button" value="hello" onclick="insert(this.form.txt1,'hello')">
<input type="button" value="my freind" onclick="insert(this.form.txt2,'hi')">
<br />
<textarea rows="7" cols="30" name="txt1">
This is sample text, click anywhere in here then
choose on of the buttons above to see text inserted.
<textarea rows="7" cols="30" name="txt2">
This is sample text, click anywhere in here then
choose on of the buttons above to see text inserted.
load more v

Basically what i want is if a user selects some text in a textarea and presses ctrl + b then the text within the selection should be surrounded by stars.,2) user selects some text and presses ctrl + b "hello this is some text" (assume the bolded part is a text selection),so basically what I want is : ,1) textarea content : "hello this is some text"

To save user history when changing a textarea's overall value, instead of:

textarea.value = newText;


document.execCommand('selectAll', false);

var el = document.createElement('p');
el.innerText = newText;

document.execCommand('insertHTML', false, el.innerHTML);

Maybe you're familiar with execCommand and wonder why we don't just use this:

document.execCommand('selectAll', false);
document.execCommand('insertText', false, newText);
load more v

Other "textarea-undefined" queries related to "Inserting text at cursor in a textarea, with Javascript"