12

The script below inserts text to the end of text area. I need to change to insert text after current cursor position in the text area.

jQuery(document).ready(function($){
    $('#addCommentImage').click(function(){
        var imageLoc = prompt('Enter the Image URL:');
        if ( imageLoc ) {
            $('#comment').val($('#comment').val() + '[img]' + imageLoc + '[/img]');
        }
        return false;
    });
});
Cœur
  • 37,241
  • 25
  • 195
  • 267
Captain Comic
  • 15,744
  • 43
  • 110
  • 148
  • 1
    possible duplicate of [Insert text into textarea with jQuery](http://stackoverflow.com/questions/946534/insert-text-into-textarea-with-jquery) – bummi Dec 02 '13 at 14:36

3 Answers3

25

if the above does not work (it didn't in my case - maybe my configuration is little bit different), here is another solution:

you can use this extension function to get the position:

(function ($, undefined) {
    $.fn.getCursorPosition = function () {
        var el = $(this).get(0);
        var pos = 0;
        if ('selectionStart' in el) {
            pos = el.selectionStart;
        } else if ('selection' in document) {
            el.focus();
            var Sel = document.selection.createRange();
            var SelLength = document.selection.createRange().text.length;
            Sel.moveStart('character', -el.value.length);
            pos = Sel.text.length - SelLength;
        }
        return pos;
    }
})(jQuery);

the usage is : var position = $("#selector").getCursorPosition()

to insert text at the position:

var content = $('#selector').val();
var newContent = content.substr(0, position) + "text to insert" + content.substr(position);
$('#selector').val(newContent);

That's all.

d.popov
  • 4,175
  • 1
  • 36
  • 47
  • Thanks, very useful for Angular JS implementation since insertAtCaret() modifications won't work in case of ng-model binding. – Denis Jul 13 '14 at 17:33
  • Works well to insert text at cursor position. Note that if the user has selected some text, it will insert before the selection, rather than replace it (tested in Chrome). – rybo111 Nov 29 '15 at 12:20
  • function getCursorPosition will change to `document.getElementById('textarea').selectionStart;` or `document.getElementById('textarea').selectionEnd;` – Fábio Zangirolami Jun 13 '16 at 19:40
15

You may checkout this answer. The insertAtCaret jquery plugin seems very nice.

Community
  • 1
  • 1
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • 5
    that actually links to an non-functioning version. The one above is the one you want. Here is the fiddle http://jsfiddle.net/rmDzu/2/ –  Mar 07 '14 at 12:19
3

I have modified various versions of these to come up with a version that places the first text before whatever you have selected and the second text after what you have selected and keep what is selected still selected. This works in chrome and FF, not in IE though.

jQuery.fn.extend({
insertAtCaret: function(myValue, myValueE){
  return this.each(function(i) {
    if (document.selection) {
      //For browsers like Internet Explorer
      this.focus();
      sel = document.selection.createRange();
      sel.text = myValue + myValueE;
      this.focus();
    }
    else if (this.selectionStart || this.selectionStart == '0') {
      //For browsers like Firefox and Webkit based
      var startPos = this.selectionStart;
      var endPos = this.selectionEnd;
      var scrollTop = this.scrollTop;
      this.value = this.value.substring(0,     startPos)+myValue+this.value.substring(startPos,endPos)+myValueE+this.value.substring(endPos,this.value.length);
      this.focus();
      this.selectionStart = startPos + myValue.length;
      this.selectionEnd = ((startPos + myValue.length) + this.value.substring(startPos,endPos).length);
      this.scrollTop = scrollTop;
    } else {
      this.value += myValue;
      this.focus();
    }
  })
    }
});

Usage: $('#box').insertAtCaret("[Before selection]", "[after]"); Also: not claiming this as mine in any way.

Tazmanian Tad
  • 193
  • 1
  • 2
  • 12