Skip to content Skip to sidebar Skip to footer

Inserting Text After Cursor Position In Text Area

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($){ $('#

Solution 1:

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;
        } elseif ('selection'indocument) {
            el.focus();
            varSel = document.selection.createRange();
            varSelLength = 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.

Solution 2:

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

Solution 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){
  returnthis.each(function(i) {
    if (document.selection) {
      //For browsers like Internet Explorerthis.focus();
      sel = document.selection.createRange();
      sel.text = myValue + myValueE;
      this.focus();
    }
    elseif (this.selectionStart || this.selectionStart == '0') {
      //For browsers like Firefox and Webkit basedvar 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.

Post a Comment for "Inserting Text After Cursor Position In Text Area"