textarea elements define the following
members in their DOM interfaces for handling their selection:
void select(); attribute unsigned long selectionStart; attribute unsigned long selectionEnd; attribute DOMString selectionDirection; void setSelectionRange(unsigned long start, unsigned long end, optional DOMString direction = "preserve");
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).
All elements to which this API applies have either a selection or a text entry cursor position at all times (even for elements that are not being rendered). User agents should follow platform conventions to determine their initial state.
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);