Tutorial: Disabling Enter Key in TextArea
Objective
- 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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | /** * 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)); addChild(ta); // // 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.
1 2 3 4 5 6 7 8 | private function ta_textInputHandler (event:TextEvent):void { // The char code for Enter is 10 if (event.text.charCodeAt() == 10) { event.preventDefault(); } } |
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.
Comments(5)






