“Enter” key in input textfield

How to catch ENTER key in input textfield?

In AS3, we can’t just use:

inputText.addEventListener(Event.KeyboardEvent.KEY_DOWN, keyDownHandler);

Because, 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.

AS3:

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

1 Comment to ““Enter” key in input textfield”

  1. By Rahyar, August 9, 2012 @ 7:39 pm

    hi
    very nice
    tanks :)

RSS feed for comments on this post. TrackBack URI

Leave a Reply