How to insert text into the textarea at the current cursor position?
Asked Answered
L

14

205

I would like to create a simple function that adds text into a text area at the user's cursor position. It needs to be a clean function. Just the basics. I can figure out the rest.

Linger answered 18/6, 2012 at 4:37 Comment(6)
possible duplicate of How do I insert some text where the cursor is?Megaton
Take a look at this answer already posted: #4457045Ahola
possible duplicate of Inserting a text where cursor is using Javascript/jqueryZestful
Interesting 2018 article: How to Insert Text Into Textarea at Cursor FastHalley
If you're looking for a simple module with undo support, try insert-text-textarea. If you need IE8+ support, try the insert-text-at-cursor package.Impertinent
Duplicate of https://mcmap.net/q/129257/-inserting-a-text-where-cursor-is-using-javascript-jquery/12860895Cookstove
J
171

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

function insertAtCursor(myField, myValue) {
    //IE support
    if (document.selection) {
        myField.focus();
        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;
    }
}
Joviality answered 18/6, 2012 at 4:44 Comment(4)
to fix "loses caret position": add inser these lines before } else { myField.selectionStart = startPos + myValue.length; myField.selectionEnd = startPos + myValue.length;Snivel
Thanks Rab for the answer and @Snivel for the fix. Here's a working example.Interchange
@user340140, your "lose caret potition" fix, only works if I give focus to the input right before the lines you suggest. It seems to be impossible to change selection on a non-focused field, at least in Chrome (current version 62.0)Valgus
There is a minor issue with this code: selectionStart is a numeric value, and thus should be compared to 0 and not '0', and probably should use ===Mader
L
111

This snippet could help you with it in a few lines of jQuery 1.9+: http://jsfiddle.net/4MBUG/2/

$('input[type=button]').on('click', function() {
    var cursorPos = $('#text').prop('selectionStart');
    var v = $('#text').val();
    var textBefore = v.substring(0,  cursorPos);
    var textAfter  = v.substring(cursorPos, v.length);

    $('#text').val(textBefore + $(this).val() + textAfter);
});
Laminated answered 31/5, 2013 at 2:5 Comment(5)
Great! Also works with 1.6 with minor modifications.Rena
But it can not replace selected textBarlow
@mparkuk: it still suffers from the "loses caret position" issue mentioned above by user340140. (Sorry, I should fix it, but I ran out of time.)Fania
Thank you providing a working fiddle. I've updated it to also reset the caret position and made it a jquery plugin: jsfiddle.net/70gqn153Skyla
This works but the cursor ends up at the wrong location.Recrudescence
A
66

New answer:

https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/setRangeText

I'm not sure about the browser support for this though.

Tested in Chrome 81.

function typeInTextarea(newText, el = document.activeElement) {
  const [start, end] = [el.selectionStart, el.selectionEnd];
  el.setRangeText(newText, start, end, 'select');
}

document.getElementById("input").onkeydown = e => {
  if (e.key === "Enter") typeInTextarea("lol");
}
<input id="input" />
<br/><br/>
<div>Press Enter to insert "lol" at caret.</div>
<div>It'll replace a selection with the given text.</div>

Old answer:

A pure JS modification of Erik Pukinskis' answer:

function typeInTextarea(newText, el = document.activeElement) {
  const start = el.selectionStart
  const end = el.selectionEnd
  const text = el.value
  const before = text.substring(0, start)
  const after  = text.substring(end, text.length)
  el.value = (before + newText + after)
  el.selectionStart = el.selectionEnd = start + newText.length
  el.focus()
}

document.getElementById("input").onkeydown = e => {
  if (e.key === "Enter") typeInTextarea("lol");
}
<input id="input" />
<br/><br/>
<div>Press Enter to insert "lol" at caret.</div>

Tested in Chrome 47, 81, and Firefox 76.

If you want to change the value of the currently selected text while you're typing in the same field (for an autocomplete or similar effect), pass document.activeElement as the first parameter.

It's not the most elegant way to do this, but it's pretty simple.

Example usages:

typeInTextarea('hello');
typeInTextarea('haha', document.getElementById('some-id'));
Adumbrate answered 14/12, 2015 at 23:36 Comment(9)
you didnt close the line with >> ; <<Parabolic
@Parabolic semicolons are optional in Javascript. Works without them too. Although, you may edit in semicolons if you want. No biggie.Adumbrate
I made a demo on JSFiddle. It also works using Version 54.0.2813.0 canary (64-bit), which is basically Chrome Canary 54.0.2813.0. Finally, if you want it to insert into the text box by ID, use document.getElementById('insertyourIDhere') in place of el in the function.Modernistic
What part of my answer is not "pure" JS? Did I forget some C++ in there?Alcestis
Hey @ErikAigner! My bad, didn't realise this question had answers by two Erik's. I meant Erik Pukinskis. I'll update the answer to better reflect that.Adumbrate
Worked for the WebView in Android.Ensanguine
You're better off attempting execCommand first and falling back to this if it fails. setRangeText will nuke the undo/redo stack. execCommand is considered obsolete by MDN, but if you care about UX, the only alternatively is to re-implement the undo/redo stack yourself.Tumulus
If you get the error setRangeText is not a function, pass the e.g. textarea object with $('.mytextarea')[0] resp. el[0].Milkwort
Thank you... However, I think it's always better to put the date of any new update.Marksman
A
49

For the sake of proper Javascript

HTMLTextAreaElement.prototype.insertAtCaret = function (text) {
  text = text || '';
  if (document.selection) {
    // IE
    this.focus();
    var sel = document.selection.createRange();
    sel.text = text;
  } else if (this.selectionStart || this.selectionStart === 0) {
    // Others
    var startPos = this.selectionStart;
    var endPos = this.selectionEnd;
    this.value = this.value.substring(0, startPos) +
      text +
      this.value.substring(endPos, this.value.length);
    this.selectionStart = startPos + text.length;
    this.selectionEnd = startPos + text.length;
  } else {
    this.value += text;
  }
};
Alcestis answered 13/11, 2013 at 18:26 Comment(7)
very nice extension! works just as expected. Thanks!Rookie
Best solution! Thank youIdol
It's not a good idea to extend the prototype of objects you don't own. Just make it a regular function and it works just as well.Impertinent
This clears the undo buffer for the edit element after setting this.value = .... Is there a way to preserve it?Deuteragonist
@Impertinent Then why have a prototype system at all. If you only work with your own types to begin with, there is no need to extend a prototype ever. Extension is what the prototype system is for.Alcestis
@ErikAigner That's not right. Before ES6 A.prototype.fn = X was the only way to have "classes"/inheritance. Just because you can extend your objects, it doesn't mean you should extend native objects. Imagine 10 years ago you implemented Array#map, then Array#map became a native API, but incompatible with yours. Now someone opens your codebase and sees [].map() and assumes it's the native API. Hello headaches and bugs.Impertinent
What JavaScript project lasts 10 years? :D But you have a point, I guess.Alcestis
U
28

A simple solution that works on firefox, chrome, opera, safari and edge but probably won't work on old IE browsers.

var target = document.getElementById("mytextarea_id")

if (target.setRangeText) {
    //if setRangeText function is supported by current browser
    target.setRangeText(data)
} else {
    target.focus()
    document.execCommand('insertText', false /*no UI*/, data);
}

setRangeText function allow you to replace current selection with the provided text or if no selection then insert the text at cursor position. It's only supported by firefox as far as I know.

For other browsers there is "insertText" command which only affect the html element currently focused and has same behavior as setRangeText

Inspired partially by this article

Upanchor answered 15/3, 2019 at 20:8 Comment(6)
This is almost the right way. The article you linked, offers a full solution as a package: insert-text-at-cursor. However I prefer execCommand because it supports undo and made insert-text-textarea. No IE support but smallerImpertinent
Unfortunately, execCommand is considered obsolete by MDN: developer.mozilla.org/en-US/docs/Web/API/Document/execCommand I don't know why, it seems to be really useful!Unlace
Yes, execCommand is used for other browsers, for firefox the function setRangeText is used instead.Upanchor
Ramast, that isn't what your code does. It will use setRangeText rather than execCommand for any browser that defines it (most). For the behaviour you describe, you need to call document.execCommand first, then check the return value. If it's false, use target.setRangeText.Tumulus
@Tumulus if setRangeText is supported then why not use it instead of execCommand? Why do I need to try execCommand first?Upanchor
I meant to match the behaviour you described: "execCommand is used for other browsers, for firefox the function setRangeText is used instead". The reason you might want to use execCommand instead is as fregante said: it supports undo. If you call setRangeText, similar to setting .value, it nukes the undo/redo stack e.g. Ctrl+Z and right-click, Undo will become unavailable.Tumulus
P
12

I like simple javascript, and I usually have jQuery around. Here's what I came up with, based off mparkuk's:

function typeInTextarea(el, newText) {
    var start = el.prop("selectionStart")
    var end = el.prop("selectionEnd")
    var text = el.val()
    var before = text.substring(0, start)
    var after  = text.substring(end, text.length)
    el.val(before + newText + after)
    el[0].selectionStart = el[0].selectionEnd = start + newText.length
    el.focus()
}

$("button").on("click", function() {
    typeInTextarea($("textarea"), "some text")
    return false
})

Here's a demo: http://codepen.io/erikpukinskis/pen/EjaaMY?editors=101

Platform answered 25/4, 2015 at 7:20 Comment(0)
A
11

Rab's answer works great, but not for Microsoft Edge, so I added a small adaptation for Edge as well:

https://jsfiddle.net/et9borp4/

function insertAtCursor(myField, myValue) {
    //IE support
    if (document.selection) {
        myField.focus();
        sel = document.selection.createRange();
        sel.text = myValue;
    }
    // Microsoft Edge
    else if(window.navigator.userAgent.indexOf("Edge") > -1) {
      var startPos = myField.selectionStart; 
      var endPos = myField.selectionEnd; 

      myField.value = myField.value.substring(0, startPos)+ myValue 
             + myField.value.substring(endPos, myField.value.length); 

      var pos = startPos + myValue.length;
      myField.focus();
      myField.setSelectionRange(pos, pos);
    }
    //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;
    }
}
Antherozoid answered 2/1, 2017 at 11:32 Comment(0)
K
9

function insertAtCaret(text) {
  const textarea = document.querySelector('textarea')
  textarea.setRangeText(
    text,
    textarea.selectionStart,
    textarea.selectionEnd,
    'end'
  )
}

setInterval(() => insertAtCaret('Hello'), 3000)
<textarea cols="60">Stack Overflow Stack Exchange Starbucks Coffee</textarea>
Koenig answered 12/10, 2019 at 17:40 Comment(0)
V
7

If the user does not touch the input after text is inserted, the 'input' event is never triggered, and the value attribute will not reflect the change. Therefore it is important to trigger the input event after programmatically inserting text. Focusing the field is not enough.

The following is a copy of Snorvarg's answer with an input trigger at the end:

function insertAtCursor(myField, myValue) {
    //IE support
    if (document.selection) {
        myField.focus();
        sel = document.selection.createRange();
        sel.text = myValue;
    }
    // Microsoft Edge
    else if(window.navigator.userAgent.indexOf("Edge") > -1) {
      var startPos = myField.selectionStart; 
      var endPos = myField.selectionEnd; 

      myField.value = myField.value.substring(0, startPos)+ myValue 
             + myField.value.substring(endPos, myField.value.length); 

      var pos = startPos + myValue.length;
      myField.focus();
      myField.setSelectionRange(pos, pos);
    }
    //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;
    }
    triggerEvent(myField,'input');
}

function triggerEvent(el, type){
  if ('createEvent' in document) {
    // modern browsers, IE9+
    var e = document.createEvent('HTMLEvents');
    e.initEvent(type, false, true);
    el.dispatchEvent(e);
  } else {
    // IE 8
    var e = document.createEventObject();
    e.eventType = type;
    el.fireEvent('on'+e.eventType, e);
  }
}

Credit to plainjs.com for the triggerEvent function

More about the oninput event at w3schools.com

I discovered this while creating an emoji-picker for a chat. If the user just select a few emojis and hit the "send" button, the input field is never touched by the user. When checking the value attribute it was always empty, even though the inserted emoji unicodes was visible in the input field. Turns out that if the user does not touch the field the 'input' event never fired and the solution was to trigger it like this. It took quite a while to figure this one out... hope it will save someone some time.

Valgus answered 16/12, 2017 at 23:3 Comment(1)
That's a very useful tip, thanks for sharing.Dayflower
A
2

The code below is a TypeScript adaptation of the package https://github.com/grassator/insert-text-at-cursor by Dmitriy Kubyshkin.


/**
 * Inserts the given text at the cursor. If the element contains a selection, the selection
 * will be replaced by the text.
 */
export function insertText(input: HTMLTextAreaElement | HTMLInputElement, text: string) {
  // Most of the used APIs only work with the field selected
  input.focus();

  // IE 8-10
  if ((document as any).selection) {
    const ieRange = (document as any).selection.createRange();
    ieRange.text = text;

    // Move cursor after the inserted text
    ieRange.collapse(false /* to the end */);
    ieRange.select();

    return;
  }

  // Webkit + Edge
  const isSuccess = document.execCommand("insertText", false, text);
  if (!isSuccess) {
    const start = input.selectionStart;
    const end = input.selectionEnd;
    // Firefox (non-standard method)
    if (typeof (input as any).setRangeText === "function") {
      (input as any).setRangeText(text);
    } else {
      if (canManipulateViaTextNodes(input)) {
        const textNode = document.createTextNode(text);
        let node = input.firstChild;

        // If textarea is empty, just insert the text
        if (!node) {
          input.appendChild(textNode);
        } else {
          // Otherwise we need to find a nodes for start and end
          let offset = 0;
          let startNode = null;
          let endNode = null;

          // To make a change we just need a Range, not a Selection
          const range = document.createRange();

          while (node && (startNode === null || endNode === null)) {
            const nodeLength = node.nodeValue.length;

            // if start of the selection falls into current node
            if (start >= offset && start <= offset + nodeLength) {
              range.setStart((startNode = node), start - offset);
            }

            // if end of the selection falls into current node
            if (end >= offset && end <= offset + nodeLength) {
              range.setEnd((endNode = node), end - offset);
            }

            offset += nodeLength;
            node = node.nextSibling;
          }

          // If there is some text selected, remove it as we should replace it
          if (start !== end) {
            range.deleteContents();
          }

          // Finally insert a new node. The browser will automatically
          // split start and end nodes into two if necessary
          range.insertNode(textNode);
        }
      } else {
        // For the text input the only way is to replace the whole value :(
        const value = input.value;
        input.value = value.slice(0, start) + text + value.slice(end);
      }
    }

    // Correct the cursor position to be at the end of the insertion
    input.setSelectionRange(start + text.length, start + text.length);

    // Notify any possible listeners of the change
    const e = document.createEvent("UIEvent");
    e.initEvent("input", true, false);
    input.dispatchEvent(e);
  }
}

function canManipulateViaTextNodes(input: HTMLTextAreaElement | HTMLInputElement) {
  if (input.nodeName !== "TEXTAREA") {
    return false;
  }
  let browserSupportsTextareaTextNodes;
  if (typeof browserSupportsTextareaTextNodes === "undefined") {
    const textarea = document.createElement("textarea");
    textarea.value = "1";
    browserSupportsTextareaTextNodes = !!textarea.firstChild;
  }
  return browserSupportsTextareaTextNodes;
}

Anyone answered 21/12, 2019 at 6:37 Comment(0)
H
1

Posting modified function for own reference. This example inserts a selected item from <select> object and puts the caret between the tags:

//Inserts a choicebox selected element into target by id
function insertTag(choicebox,id) {
    var ta=document.getElementById(id)
    ta.focus()
    var ss=ta.selectionStart
    var se=ta.selectionEnd
    ta.value=ta.value.substring(0,ss)+'<'+choicebox.value+'>'+'</'+choicebox.value+'>'+ta.value.substring(se,ta.value.length)
    ta.setSelectionRange(ss+choicebox.value.length+2,ss+choicebox.value.length+2)
}
Huysmans answered 3/9, 2016 at 7:48 Comment(0)
N
0
/**
 * Usage "foo baz".insertInside(4, 0, "bar ") ==> "foo bar baz"
 */
String.prototype.insertInside = function(start, delCount, newSubStr) {
    return this.slice(0, start) + newSubStr + this.slice(start + Math.abs(delCount));
};

$('textarea').bind("keydown keypress", function (event) {
    var val = $(this).val();
    var indexOf = $(this).prop('selectionStart');
    if(event.which === 13) {
        val = val.insertInside(indexOf, 0,  "<br>\n");
        $(this).val(val);
        $(this).focus();
    }
});
Nobe answered 5/12, 2017 at 7:28 Comment(1)
While this may answer the question, it is better to explain the essential parts of the answer and possibly what was the problem with OPs code.Goddord
A
0

Extending on Adriano's answer, we may also take cursor end into consideration which will make the "replace text" work

$('input[type=button]').on('click', function() {
    var cursorStart = $('#text').prop('selectionStart');
    var cursorEnd = $('#text').prop('selectionEnd');
    var v = $('#text').val();
    var textBefore = v.substring(0,cursorStart);
    var textAfter  = v.substring(cursorEnd);
    $('#text').val(textBefore + $(this).val() + textAfter);
});
Apian answered 14/5, 2022 at 6:58 Comment(0)
E
-1

Changed it to getElementById(myField):

function insertAtCursor(myField, myValue) {
    // IE support
    if (document.selection) {
        document.getElementById(myField).focus();
        sel = document.selection.createRange();
        sel.text = myValue;
    }
    // MOZILLA and others
    else if (document.getElementById(myField).selectionStart || document.getElementById(myField).selectionStart == '0') {
        var startPos = document.getElementById(myField).selectionStart;
        var endPos = document.getElementById(myField).selectionEnd;
        document.getElementById(myField).value =
                document.getElementById(myField).value.substring(0, startPos)
                + myValue
                + document.getElementById(myField).value.substring(endPos, document.getElementById(myField).value.length);
    } else {
        document.getElementById(myField).value += myValue;
    }
}
Exocentric answered 12/11, 2013 at 2:42 Comment(3)
That's going to hit the DOM way more than you need to.. storing myfield as a local is much better for performanceDnepropetrovsk
Wow, really way too much repetition of document.getElementById(myField)! Do it once at the top and use a variable name. How many times in a row do you intend to redundantly lookup the same element?Pyrometallurgy
Thanks for helping ,i got the solutionMccarley

© 2022 - 2024 — McMap. All rights reserved.