Skip to content Skip to sidebar Skip to footer

Insert A String In A Textarea At Cursor Position With Some Changes

I'm been searching for a script to insert a string in a textarea at the cursor position. I came across the following script by Tim Down. Can someone help me to implement it in my c

Solution 1:

Try this function

// We've extended one function in jQuery to use it globally.
$(document).ready(function(){  
  jQuery.fn.extend({
insertAtCaret: function(myValue){
  returnthis.each(function(i) {
    if (document.selection) {
      //For browsers like Internet Explorerthis.focus();
      var sel = document.selection.createRange();
      sel.text = myValue;
      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(endPos,this.value.length);
      this.focus();
      this.selectionStart = startPos + myValue.length;
      this.selectionEnd = startPos + myValue.length;
      this.scrollTop = scrollTop;
    } else {
      this.value += myValue;
      this.focus();
    }
  });
}
});


    $('#spanString').val("");
$("span").click(function(){
    
    $('#spanString').insertAtCaret("? " + $("#"+this.id).html());
});
$('button').click(function(){
    $('#spanString').insertAtCaret( '12365' );
})
});
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><spanclass="spanClass"id="span1">String1</span><spanclass="spanClass"id="span2">String2</span><spanclass="spanClass"id="span3">String3</span><spanclass="spanClass"id="span4">String4</span><spanclass="spanClass"id="span5">String5</span><spanclass="spanClass"id="span6">String6</span><textareaid="spanString"></textarea>

UPDATE

Add ? just before you set span value to textarea like this

$('#spanString').insertAtCaret("? " + $("#"+this.id).html());

Have updated code accordingly.

Post a Comment for "Insert A String In A Textarea At Cursor Position With Some Changes"