Monday, 8 April 2013

Inserting Text at cursor position in Textarea


We can insert simple text in Text area at cursor position using javascript

Below is the snippet.

var myTextArea = document.getElementById("mymessage");
var textInArea = myTextArea.value;
var textToInsert = '$Simple Text$';
var caretPosition = myTextArea.selectionStart;
myTextArea.value = textInArea.substring(0, caretPosition)
    + textToInsert  + textInArea.substring(caretPosition);


'selectionStart' property provides the cursor position in Textarea.

Simillarly getting cursor position in JQuery

$('#mymessage').prop("selectionStart")


Try Example:

3 comments:

  1. Thank you! this simple code very useful for me!!!
    Thank you from Ukraine!

    ReplyDelete
  2. Very useful information that you have shared and it is very useful to me. Thanks for sharing the information with us.
    kindle mobi formatting services

    ReplyDelete