keyboard ENTER key dont work for tlf text input?

1.6k Views Asked by At

i have a tlf text input in stage,i want dispatch ahndler for this object when enter key in press, but i can't do this

import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
import flash.display.Sprite;
tlf.addEventListener(KeyboardEvent.KEY_DOWN,handler);
function handler(event:KeyboardEvent)
{
    if (event.keyCode = Keyboard.ENTER)
    {
        trace('enter key is detect');
    }
}

Where is my mistake ?

3

There are 3 best solutions below

2
On BEST ANSWER

The operator '=' is for assignation, not comparison. The EQUAL TO operator is '=='. So, in your code:

 if (event.keyCode = Keyboard.ENTER)

should be:

if (event.keyCode == Keyboard.ENTER)

Assuming you have a text input on the stage, and it's called 'tlf', this will work:

import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
import flash.display.Sprite;

tlf.addEventListener(KeyboardEvent.KEY_DOWN,key_down_handler);

function key_down_handler(ev:KeyboardEvent)
{
    if (ev.keyCode == Keyboard.ENTER)
    {
        trace('enter key!!!!');
    }
}

One advice: try to give your variables and functions more meaningful names, for example instead of just 'tlf', if it's an input textfield: 'tlf_input_text' and instead of just 'handler': 'key_down_handler' or something like this. It will help others (and yourself, in the long run) to read and understand your code.

0
On

TLFText handles the Enter Key differently than the classic text. For TLF use this:

tlf.addEventListener(TextEvent.TEXT_INPUT, textInputHandler);

function textInputHandler(evt:TextEvent):void {
    if (evt.text=="\r") {
        trace('THE ENTER KEY WORKS NOW');
    }
}
0
On

I have just experienced the same issue.

The best way to solve it for me, was to add (useCapture=true) to the event listener.

So this: tlf.addEventListener(KeyboardEvent.KEY_DOWN,handler);

Becomes this: tlf.addEventListener(KeyboardEvent.KEY_DOWN,handler,true);

I don't believe the 2 answers previously provided are satisfactory. One wants the coder to stop using TLF, the other wants him to stop using KeyboardEvent.

Reference: http://forums.adobe.com/thread/826424