Skip to content Skip to sidebar Skip to footer

Fetching Cursor Location And Highlighted Text In Textarea Using Jquery

Having a textarea in a form I am trying to do several things: fetch the current location of the cursor within the text area fetch the current selection within the textarea insert

Solution 1:

There are many jQuery plugins for this. Here's a good one I've used before:

http://plugins.jquery.com/project/a-tools


To fetch the current location of the cursor within the text area:

$("textarea").getSelection().start;

To fetch the current selection within the textarea:

$("textarea").getSelection();

this returns an object like this:

{
    start: 1, // where the selection starts
    end: 4, // where the selection ends
    length: 3, // the length of the selection
    text: 'The selected text'
}

To insert some text at the current cursor location:

$("#textarea").insertAtCaretPos("The text to insert");

To replace the current selection by some other text:

$("#textarea").replaceSelection('This text will replace the selection');

Post a Comment for "Fetching Cursor Location And Highlighted Text In Textarea Using Jquery"