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.

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

  2. Glad it’s aaalmost wonkrig!First up, I realized there was no way to manually set which menu item was selected. Check the GoogleCode link in the post for a version 1.2 with a new function called setSelected(). If you download the new v1.2 package file, it’ll show the usage although its really only one line fishEyeMenu.setSelected( menu2 ); or whichever default menu item you want to be selected and that should be called in your Main() function. The setSelected method will automatically trigger the SELECTED_CHANGED event, so whatever is supposed to happen when you click a new event, it’ll trigger that as well.edit: Oh and as for TextField getting the mouse hand cursor as far as I know, that’s not possible with textfields. What you would probably want to do is create a MovieClip or Sprite and add the textField into the MC/Sprite then push the MC/Sprite into fishEyeMenu instead of the menu1/menu2 TextFields. Then you’d just want to make sure you added myMC.useHandCursor = true;

Leave a Reply

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