5

I have a textbox with some words and text.The thing I want to do is this that when the user clicks on a button add some words to the text of the textbox from the current position of the pointer.How to do this? This is the textbox and the button:

<textarea id="txt" rows="15" cols="70">There is some text here.</textarea>
<input type="button" id="btn" value="OK" />
Hamid Reza
  • 2,913
  • 9
  • 49
  • 76
  • possible duplicate of [Inserting a text where cursor is using Javascript/jquery](http://stackoverflow.com/questions/1064089/inserting-a-text-where-cursor-is-using-javascript-jquery) – Denys Séguret Apr 12 '13 at 16:38
  • Check this answer out: http://stackoverflow.com/questions/1064089/inserting-a-text-where-cursor-is-using-javascript-jquery – tymeJV Apr 12 '13 at 16:38
  • possible duplicate of [Insert text into textarea with jQuery](http://stackoverflow.com/questions/946534/insert-text-into-textarea-with-jquery) – mplungjan Apr 12 '13 at 16:39
  • Full working function at http://stackoverflow.com/questions/3308292/inserting-text-at-cursor-in-a-textarea-with-javascript/3308539#3308539 – Niels Keurentjes Apr 12 '13 at 16:40

2 Answers2

14

Maybe a shorter version, http://jsfiddle.net/NaHTw/4/ would be easier to understand?

jQuery("#btn").on('click', function() {
    var caretPos = document.getElementById("txt").selectionStart;
    var textAreaTxt = jQuery("#txt").val();
    var txtToAdd = "stuff";
    jQuery("#txt").val(textAreaTxt.substring(0, caretPos) + txtToAdd + textAreaTxt.substring(caretPos) );
});
quik_silv
  • 2,397
  • 2
  • 15
  • 21
  • Here's one updated to use a textbox instead of a textarea: http://jsfiddle.net/NaHTw/1049/ – pkr Dec 20 '17 at 23:32
11

Quite coincident, I just answer a similar question a few minutes ago. You can use a custom function like this:

jQuery.fn.extend({
insertAtCaret: function(myValue){
  return this.each(function(i) {
    if (document.selection) {
      //For browsers like Internet Explorer
      this.focus();
      sel = document.selection.createRange();
      sel.text = myValue;
      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(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();
    }
  })
}
});

Basically, this plugin allows you to insert a piece of text at caret of multiple textbox or textarea . You can use it like this:

 $('#element1, #element2, #element3, .class-of-elements').insertAtCaret('text');

Working Demo

Community
  • 1
  • 1
Eli
  • 14,779
  • 5
  • 59
  • 77