views:

3080

answers:

5

I'm trying to handle a focus event on a TextField so I can select all the text when focusing (tab or click). Seems like I'm doing something wrong here ?

txtTextField.addEventListener(FocusEvent.FOCUS_IN, handleFocusIn);
function handleFocusIn() {
 //select all text here
}
+1  A: 

Your handleFocusIn should have the signature

function handleFocusIn(event:FocusEvent) // or just Event
Vinay Sajip
A: 

Yeah I know, but this was something I just forgot to add in the question here :)

yens resmann
You also forgot to mention what actually happens, whether you get any error messages, the code you used to select all the text ...
Vinay Sajip
My code for selecting text is ok, but the function handleFocusIn isn't fired when focusing the textField.
yens resmann
+1  A: 

I had a similar problem at the prototype phase of a development (in Flash). A textfield wasn't firing FocusEvent.FOCUS_OUT events at all. The problem was i had a Button component on the stage. As soon as i replaced that flash Button component instance with a custom button a created from scratch, i got it to work. I haven't been able to find this bug and the solution over the internet.

With a Button component on stage i get FOCUS_IN event only the first time i click on it. After that i don't get neither FOCUS_OUT nor FOCUS_IN events fired.

I hope this would help someone in any way.

vitaLee
A: 

I needed the same thing, to select the contents of a textfield when it receives focus.

I tried:

A) Simply selecting after a FocusEvent. This doesn't seem to work (my guess is that FocusEvents are fired before the mouse click is being processed, which in turn will undo the selection).

B) Selecting on every mouse click. This works, but this is very annoying for a user who wants to select only a part of the text later, since this attempt will always result in -all- the content being selected.

The following workaround seems to work though:

    myTextField.addEventListener(MouseEvent.CLICK, selectAllOnce);

    function selectAllOnce(e:MouseEvent) {
        e.target.removeEventListener(MouseEvent.CLICK, selectAllOnce);
        e.target.addEventListener(FocusEvent.FOCUS_OUT, addSelectListener);
        selectAll(e);
    }

    function addSelectListener(e:FocusEvent) {
        e.target.addEventListener(MouseEvent.CLICK, selectAllOnce);
        e.target.removeEventListener(FocusEvent.FOCUS_OUT, addSelectListener);
    }

    function selectAll(e:Event) {
        e.target.setSelection(0, e.target.getLineLength(0));
    }

Hope that helps. I personally think it would be most logical if adobe simply added an option for this for the TextField object.

A: 

I am doing my handler like this. Works like a charm:

private function onFocusIn(e:FocusEvent):void 
{
    setTimeout(title.setSelection, 100, 0, e.target.text.length);           
}
Fehaar