textarea elements define
the following members in their DOM interfaces for handling their
void select(); attribute unsigned long selectionStart; attribute unsigned long selectionEnd; attribute DOMString selectionDirection; void setSelectionRange(unsigned long start, unsigned long end, optional DOMString direction);
These methods and attributes expose and control the selection of
textarea text fields.
Selects everything in the text field.
selectionStart[ = value ]
Returns the offset to the start of the selection.
Can be set, to change the start of the selection.
selectionEnd[ = value ]
Returns the offset to the end of the selection.
Can be set, to change the end of the selection.
selectionDirection[ = value ]
Returns the current direction of the selection.
Can be set, to change the direction of the selection.
The possible values are "
backward", and "
setSelectionRange(start, end [, direction] )
Changes the selection to cover the given substring in the given direction. If the direction is omitted, it will be reset to be the platform default (none or forward).
Characters with no visible rendering, such as U+200D ZERO WIDTH JOINER, still count as characters. Thus, for instance, the selection can include just an invisible character, and the text insertion cursor can be placed to one side or another of such a character.
var selectionText = control.value.substring(control.selectionStart, control.selectionEnd);
To add some text at the start of a text control, while maintaining the text selection, the three attributes must be preserved:
var oldStart = control.selectionStart; var oldEnd = control.selectionEnd; var oldDirection = control.selectionDirection; var prefix = "http://"; control.value = prefix + control.value; control.setSelectionRange(oldStart + prefix.length, oldEnd + prefix.length, oldDirection);