Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a text to a textbox from the current position of the pointer with jquery?

Tags:

jquery

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" />
like image 825
Hamid Reza Avatar asked Apr 12 '13 16:04

Hamid Reza


2 Answers

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) );
});
like image 124
quik_silv Avatar answered Oct 16 '22 19:10

quik_silv


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

like image 25
Eli Avatar answered Oct 16 '22 19:10

Eli