Skip to content

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 Comments

  1. colin

    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);
    }

    Posted on 06-Dec-09 at 11:35 pm | Permalink
  2. hugh

    rad colin, thanks! that would definitely be a better way to handle it.

    Posted on 07-Dec-09 at 12:04 am | Permalink

Post a Comment

Your email is never published nor shared. Required fields are marked *
*
*