Retrieve/Replace Selected Text With jQuery

Posted By : todd sharp Posted At : July 31, 2009 2:02 PM Posted In: jQuery

0

Here's another very helpful jQuery plugin that I found recently. The jQuery fieldSelection plugin gives you a simple API to retrieve and replace the currently selected text in an input or textarea.

Once you include the plugin you just do a simple call to retrieve the selection:

var s = $('#foo').getSelection();
console.dir(s);

The code above would dump an object to the console with the following elements:

  • id
  • start
  • end
  • length
  • text

To replace the current selection you would call replaceSelection like so:

$('#foo').replaceSelection('new text',true);

I'm using this plugin for a top secret enhancement for BlogCFC that I hope will be released very soon. More on that in the next few days.

Comments (0)