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.
























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.
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.
They have done really wonderful work here
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!
hey i hav one different way to disable enter key..
instead of putting the ascii code for enter key..
jst put the below code
if(event.text==”\n”)
event.preventDefault();