Recipe 9.21. Selecting
Text with ActionScript
Problem
You want
to highlight a portion of the text within a text field.
Solution
Use the TextField.setSelection( )
method.
Discussion
The TextField.setSelection( ) method
highlights a portion of the text in the text field. The setSelection( ) method takes two
parameters:
startIndex
-
The beginning, zero-relative index of the text
to highlight.
endIndex
-
The index of the character after the text to
highlight.
For the selection to work, the text field must
have focus, which you can set by using Stage.focus, as
discussed in Recipe
9.20:
stage.focus = field; // Set the focus to the text field
field.text = "this is example text"; // Set the text value
field.setSelection(0, 4); // Highlight the word "this"
Use the read-only selectionBeginIndex
and selectionEndIndex properties to retrieve the indices
of the selected character range.
See Also
Recipes 9.20
and 9.23
|