Search code examples
flashactionscript-3eventskeyboardtlf

keyboard ENTER key dont work for tlf text input?


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 ?


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.