Question

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 ?

Was it helpful?

Solution

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.

OTHER TIPS

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');
    }
}

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top