Text Selection Discovery

I was wracking my brain on and off for about a week trying to get a field to select all the text in it when it achieves focus. This happens automatically when you tab to it, but when you click in it, it sets the caret wherever you’re clicked.

Initially I was convinced that FocusEvent.FOCUS_IN should do the trick. In fact, I’m still convinced it is, but it doesn’t work.

var tmp:TextField = new TextField();
tmp.addEventListener(FocusEvent.FOCUS_IN,focusText);
tmp.htmlText = “test text”;
tmp.autoSize = “left”;
tmp.selectable = true;
tmp.type = “input”;
tmp.border = true;
tmp.x = 50;
tmp.y = 50;
addChild(tmp);
function focusText(_fevt:FocusEvent):void{
trace(_fevt.target.text);
var tf:TextField = TextField(_fevt.target);
tf.setSelection(0,tf.length);
}

This doesn’t work. Such a shame.

Anyway, Todd Fraser over here at Organic gave me one of those, “wait, MouseEvent.CLICK didn’t work?” with one eyebrow raised. And although I had to admit I hadn’t even bothered with MouseEvent.CLICK because I assumed FocusEvent.FOCUS_IN should work. Don’t discount what you might consider “ol’ timey” ways of doing things.

var tmp:TextField = new TextField();
tmp.addEventListener(MouseEvent.CLICK,focusText);
tmp.htmlText = “test text”;
tmp.autoSize = “left”;
tmp.selectable = true;
tmp.type = “input”;
tmp.border = true;
tmp.x = 50;
tmp.y = 50;
addChild(tmp);
function focusText(_fevt:MouseEvent):void{
trace(_fevt.target.text);
var tf:TextField = TextField(_fevt.target);
tf.setSelection(0,tf.length);
}

Shoot, dawg.

2 thoughts on “Text Selection Discovery”

  1. here's another workaround hugh (this one works better if the user needs to select content in the text field after giving it focus):

    protected function focusListener (e:FocusEvent):void {
    setTimeout(yourTextField.setSelection, 50, 0, yourTextField.length);
    }

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>