views:

3251

answers:

3

Hello,

I want to catch the enter key press when the user is filling an input text field in AS3. I think I have to do something like this:

    inputText.addEventListener(Event. ? , func);
    function func(e:Event):void{
       if(e. ? == "Enter"){
          doSomething();
       }
    }

But I can't find the best way to do this. By the way, the input text has a restriction:

inputText.restrict = "0-9";

Should I add the enter key to the restrictions?

inputText.restrict = "0-9\n";

Thanks in advance.

+1  A: 

Are you using a textfield, or a TextInput?

The TextInput dispatches a Enter-event, when the enter is pressed. More on this can be found at http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/fl/controls/TextInput.html#event:enter

I'm not sure how this works for a Textfield.

Pbirkoff
I use the Text tool, and then i set that the box is an Input Text.I tried to use inputText.enter = function (e:Object){ bla } but it throws Error #1056: Can't create property enter in flash.text.TextField.Thanks.
Jonathan Barbero
+6  A: 

I think that the only way to actually do what you want is a bit complex.

Basically, you can't get any event from the regular TextField that would be fired when the Enter key is pressed. You have to do work around...

One idea would be to listen the textfield for focus events. When it has focus, you add a listener to the stage for key board events and check if the pressed key is Enter, if so fire your action, else skip.

Sample code:

inputText.addEventListener(FocusEvent.FOCUS_IN,textInputHandler);
inputText.addEventListener(FocusEvent.FOCUS_OUT,textInputHandlerOut);

function textInputHandler(event:FocusEvent):void {
    //our textfield has focus, we want to listen for keyboard events.
    stage.addEventListener( KeyboardEvent.KEY_DOWN, keyDownHandler);
}

function textInputHandlerOut(event:FocusEvent):void {
    //our textfield lost focus, remove our listener.
    stage.removeEventListener( KeyboardEvent.KEY_DOWN, keyDownHandler);
}

function keyDownHandler( e:KeyboardEvent ):void{
    //a key was pressed, check if it was Enter => charCode 13.
    if( e.charCode == 13 ){
      //ok, enter was pressed. Do your thing.
      trace("We pressed enter, doSomething" )
    }
}
goliatone
I used:inputText.addEventListener(KeyboardEvent.KEY_DOWN,handler);function handler(event:KeyboardEvent){ if(event.charCode == 13){ doSomething(); }}And it works. Thanks.
Jonathan Barbero
A: 

I am really new to AS, like to ask where and how to insert that code below?

Daniel
You could put this code in the frame where the text input or text field are. The frames are in the time line. Go to the first frame, open the window "Actions" and paste the code there. Change the names of the variables to the name that you put to the text input or text field.
Jonathan Barbero