Corrected Answer
You can easily listen for keyboard events occurring when the textfield is focused.
Just add a KEY_DOWN event directly to the textfield, and then do whatever you want.
// get key presses only when the textfield is being edited
inputText.addEventListener(KeyboardEvent.KEY_DOWN,handler);
function handler(event:KeyboardEvent){
// if the key is ENTER
if(event.charCode == 13){
// your code here
doSomething();
}
}
On a separate note, textfields also send other useful events:
- When modified by the user (if its an input textfield) -- Event.CHANGE
- When text is typed by the user (if its an input textfield) -- TextEvent.TEXT_INPUT
- When a link is clicked (if its HTML text) -- TextEvent.LINK
- When scrolled by the user (if its multiline and the contents don't fit) -- Event.SCROLL
Previous Wrong Answer:
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" )
}
}