Skip to main content
FlashTapper
Inspiring
June 28, 2012
Answered

How does setFocus() method work in AS3?

  • June 28, 2012
  • 1 reply
  • 3555 views

Hi everyone. I will try to keep this as simple as i can.

I'm trying to use the setFocus method for highlighting the default text in a text input field.

So bascially when user clicks on that text field - the text is highlighted and they can type over it. Currently have about 16 text fields with something akin to 'insert text here' as a prompt for our lower ICT demographic of users and it's a bit tedious to expect the user to highlight the text in each field and then type over it.

Can be performed awesomly if you tab through the text fields but I would not expect many users to use this method.

I've looked around on the net for solutions to this using as3 but I haven't found anything that has worked for me. I'd be very grateful for a suggestion or a point in the right direction....

Thanks

This topic has been closed for replies.
Correct answer Ned Murphy

If you want to have clicking a textfield end up with the text inside it selected, try the following...

tf1.addEventListener(MouseEvent.MOUSE_UP, selectText);

tf2.addEventListener(MouseEvent.MOUSE_UP, selectText);

tf3.addEventListener(MouseEvent.MOUSE_UP, selectText);

etc...

function selectText(evt:MouseEvent):void {
    evt.currentTarget.setSelection(0,evt.currentTarget.length-1);
}

1 reply

Ned Murphy
Ned MurphyCorrect answer
Legend
June 28, 2012

If you want to have clicking a textfield end up with the text inside it selected, try the following...

tf1.addEventListener(MouseEvent.MOUSE_UP, selectText);

tf2.addEventListener(MouseEvent.MOUSE_UP, selectText);

tf3.addEventListener(MouseEvent.MOUSE_UP, selectText);

etc...

function selectText(evt:MouseEvent):void {
    evt.currentTarget.setSelection(0,evt.currentTarget.length-1);
}

FlashTapper
Inspiring
June 28, 2012

Thanks Ned...did the trick

Although I'm not sure what you mean about the 'lenght-1' but - I jsut got rid of the -1 as it was not selecting all of my text.

Also I think I'm going to set up an array and run a for while loop to assign the functions to all of my textfields - there are about 19 of them!

There is now way I'm going to set up all the even listeners for all of them individually.

Cheers.

Ned Murphy
Legend
June 28, 2012

You're welcome.  If you look up the setSelection method of the TextField class you might be able to understand why the -1 was used.  If you name the textfields using a numeric progression you won't need to create an array.  You can use bracket notation to target them in that loop.