O'Reilly logo

Facebook Cookbook by Jay Goldman

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Textbox Selections

Problem

I need to get or set the selection (or contents) of a textarea or an input of type text.

Solution

Facebook Platform provides a pair of methods for getting and setting the selection in text fields:

obj.getSelection()

Returns an object with start and end properties:

selIndexes = document.getElementById('myTextarea').getSelection();
selStart = selIndexes.start;
selEnd = selIndexes.end;
obj.setSelection()

Sets the selection within the text field, taking a required start and an optional end:

// Put the cursor into the field after the 5th character
document.getElementById('myTextarea).setSelection(5);

// Select the 5th to 10th characters
document.getElementById('myTextarea).setSelection(5,10);

Discussion

This isn’t much different from the way you would access the same properties through normal JavaScript, except than an abstraction layer has been added to smooth over Internet Explorer’s lack of support for selectionStart and selectionEnd. The Fabulous Selection Getter and Setter twins will help you do all kinds of amazing manipulation of the cursor and text selection regions, but they won’t help you actually retrieve the value of the text in the field (or, by extension, of the selected text in the field). Here’s a useful function that accepts the id of a text field and returns the full value if nothing is selected, or returns just the selected text if something is:

function getText(targetField){ var indexes = document.getElementById(targetField).getSelection(); var fullText ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required