Tutorial: Disabling Enter Key in TextArea

  • Learn how to disable the Enter key from working in a TextArea component.
  • View Demo
Files Required
Let’s Get Started!

Now I know what you are probably thinking; why would I want to disable the Enter key in a TextArea? Well I found one use case: The information that you want your user to enter can be quite lengthy and you want to display everything that the user had typed, but TextArea allows the Enter key to work. You wish it would operate like a TextInput component.

Let’s start by examining the init() function.

 * Initialise
private function init ():void 
    // create the text area
    ta = new TextArea();
    ta.move(Main.PADDING, Main.PADDING);
    ta.setSize(stage.stageWidth - (Main.PADDING * 2), stage.stageHeight - (Main.PADDING * 2));
    // Add the event listeners
    ta.textField.addEventListener(TextEvent.TEXT_INPUT, ta_textInputHandler, false, 0, true);

After creating the TextArea, we have to listen to the TextEvent.TEXT_INPUT event to track whatever the user had just typed.

IMPORTANT NOTE: We listen to the event from the textField property of the TextArea instance, and not the TextArea instance itself. If you do otherwise, it will not work.

private function ta_textInputHandler (event:TextEvent):void
    // The char code for Enter is 10
    if (event.text.charCodeAt() == 10) 

In the event handler, we will track the text that is trying to get itself added to the textField. When the conditional is true, we simply prevent it from happening by using the preventDefault() method of event argument.

Final Note

For more information regarding preventDefault(), you can read the documentation. :)

About Flashmech

I have too many things in plans for my own good. But well, that's me. :) I love God, praise Him, and trust that He has the best plans in life for me.
This entry was posted in ActionScript, Tutorials. Bookmark the permalink.

5 Responses to Tutorial: Disabling Enter Key in TextArea

  1. dVyper says:

    Nice tutorial :)

    What’s kind of weird is that the example works fine, but in Chrome, if you right-click the ‘View Demo’ link and open in a new tab, the TextArea doesn’t expand as it should. Looks like a Chrome only bug.

  2. flashmech says:

    You are right! Thanks for pointing it out!
    I guess to view the example “properly” on Chrome, you have to refresh it. Tried and it worked. 😉

  3. marc andrew says:

    They have done really wonderful work here

  4. I treked around the Internet for near an hour looking for what seemed to me like a very simple function. Thank you very much! You saved my day!

  5. eric says:

    hey i hav one different way to disable enter key..

    instead of putting the ascii code for enter key..
    jst put the below code