Preventing line feeds in a TextArea control in Flex
The following example shows how you can prevent a user from pressing Enter in a Flex TextArea control by listening for the textInput event and checking the TextEvent object’s text property for a newline character (“\n”).
<?xml version="1.0" encoding="utf-8"?> <!-- http://blog.flexexamples.com/2008/03/07/preventing-line-feeds-in-a-textarea-control-in-flex/ --> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical" verticalAlign="middle" backgroundColor="white"> <mx:Script> <![CDATA[ private function textArea_textInput(evt:TextEvent):void { if (evt.text == "\\n") { evt.preventDefault(); } } ]]> </mx:Script> <mx:TextArea id="textArea" verticalScrollPolicy="on" width="160" height="120" textInput="textArea_textInput(event);"> <mx:text>The quick brown fox jumped over the lazy dog.</mx:text> </mx:TextArea> </mx:Application>
View source is enabled in the following example.
Update 8/19/2008: If you want to prevent a user from pasting text with a carriage return/linefeed, you could listen for the change event and use the String class’s replace() method to replace any newline (“\n”) or linefeed (“\r”) with an empty string, as seen in the following example:
<?xml version="1.0" encoding="utf-8"?> <!-- http://blog.flexexamples.com/2008/03/07/preventing-line-feeds-in-a-textarea-control-in-flex/ --> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical" verticalAlign="middle" backgroundColor="white"> <mx:Script> <![CDATA[ private function textArea_textInput(evt:TextEvent):void { if (evt.text == "\\n") { evt.preventDefault(); } } private function textArea_change(evt:Event):void { textArea.text = textArea.text.replace(/\\n|\\r/ig, ""); } ]]> </mx:Script> <mx:TextArea id="textArea" text="The quick brown fox jumped over the lazy dog." verticalScrollPolicy="on" width="100%" height="100%" textInput="textArea_textInput(event);" change="textArea_change(event);" /> </mx:Application>
Peter deHaan
Peter deHaan currently works for Adobe on the Flex SDK QA team. While not working on Flex, Flash, and ColdFusion applications, Peter enjoys making up bios and writing in 3rd person. Peter's rarely updated blog can be found at blogs.adobe.com/pdehaan/, actionscriptexamples.com, airexamples.com, and coldfusionexamples.com.
-
Add Widgets (Content Sidebar)
This is your Content Sidebar. Edit this content that appears here in the widgets panel by adding or removing widgets in the Content Sidebar area.
21 Responses to Preventing line feeds in a TextArea control in Flex
Leave a Reply Cancel reply
-
Categories
- Accordion
- AccordionHeader
- ActionScript
- AddChild
- AdvancedDataGrid
- Alert
- alpha
- Animate
- AnimateProperties
- Application
- Application (Spark)
- ArrayCollection
- BarChart
- baseColor
- beta
- beta1
- beta2
- Bitmap
- Bitmap/BitmapData
- BitmapData
- BitmapFill
- BitmapFill (Spark)
- BitmapGraphic
- BitmapImage
- BitmapImage (Spark)
- BitmapImageResizeMode
- Border (Spark)
- BorderContainer (Spark)
- Box
- BuildInfo
- Button
- Button (Spark)
- ButtonBar
- ButtonBar (Spark)
- ByteArray
- Camera
- Charting
- CheckBox
- CheckBox (Spark)
- ClassFactory
- CollectionEvent
- Color
- ColorPicker
- ColorUtil
- ComboBox
- ComboBoxArrowSkin
- Compiler
- Component
- Component (Spark)
- Configuration
- Container
- ContextMenu
- ContextMenuEvent
- ContextMenuItem
- CSSCondition
- CSSSelector
- CSSStyleDeclaration
- CurrencyFormatter
- CursorManager
- Data Binding
- DataGrid
- DataGrid (Spark)
- DataGridColumn
- Date
- DateBase
- DateChooser
- DateField
- DateFormatter
- Debugging
- DefaultComplexItemRenderer
- DefaultTileListEffect
- DropDownList
- DropDownList (Spark)
- DropDownListButtonSkin
- DropDownListSkin
- DropShadowFilter
- E4X
- Effects
- Ellipse
- EmailValidator
- Embed
- Event
- Fade
- FileFilter
- FileReference
- fill
- Filters
- Flash
- Flash Integration
- FlashVars
- Flex 3 SDK
- Flex Builder
- Flex Builder 3
- Flex SDK
- Flex4
- FLVPlayback
- FocusManager
- FontLookup
- Fonts
- Form
- Form (Spark)
- FormHeading (Spark)
- FormItem
- FormItem (Spark)
- Forms
- FTETextField (Spark)
- FullScreen
- FullScreenEvent
- FxAnimateColor
- FxButtonBar
- FxCheckBox
- FXG
- FxHScrollBar
- FxHSlider
- FxList
- FxNumericStepper
- FxRadioButton
- FxRotate3D
- FxScroller
- FxTextArea
- FxTextInput
- FxToggleButton
- FxVScrollBar
- FxVSlider
- getStyleDeclaration()
- GradientEntry
- Graphic (Spark)
- HBox
- HDividedBox
- HGroup (Spark)
- HorizontalLayout
- HorizontalList
- HSBColor (Spark)
- HScrollBar (Spark)
- HSlider
- HSlider (Spark)
- HTML template
- ID3Info
- Image
- Image (Spark)
- ImageSnapshot
- itemRenderer
- JointStyle
- Label
- Label (Spark)
- Legend
- LegendItem
- LigatureLevel
- Line
- LinearGradientStroke
- LineScaleMode
- LinkBar
- LinkButton
- List
- List (Spark)
- Menu
- MenuBar
- Metadata
- MetadataEvent
- Model
- Mouse
- MouseCursor
- MouseEvent
- Move
- Namespace
- NavigatorContent (Spark)
- needsSWF
- NetConnection
- NetStream
- Nightly Builds
- NumberBaseRoundType
- NumberFormatter
- NumberValidator
- NumericCompare
- NumericStepper
- NumericStepper (Spark)
- ObjectProxy
- ObjectUtil
- paddingLeft
- paddingRight
- Panel
- Panel (Spark)
- Parallel
- Path
- PieChart
- PieSeries
- PieSeriesItem
- PopUpAnchor (Spark)
- PopUpButton
- PopUpManager
- ProgrammaticSkin
- ProgressBar
- PropertyChangeEvent
- QName
- RadialGradient
- RadioButton
- RadioButton (Spark)
- RadioButtonGroup
- RadioButtonGroup (Spark)
- Rect
- RegExp
- Regular Expressions
- Repeater
- RichEditableText
- RichText
- RichText (Spark)
- RichTextEditor
- Rotate
- Rotate3D (Spark)
- Scroller (Spark)
- Sequence
- setStyle()
- SimpleText
- SimpleText (Spark)
- skinClass
- Slider
- SliderEvent
- SolidColor
- SolidColorStroke
- Sort
- SortField
- Sound
- SoundEffect
- Spinner (Spark)
- SpriteVisualElement (Spark)
- StageDisplayState
- States
- StringUtil
- StringValidator
- StyleManager
- Styles
- SWFLoader
- SWFObject
- System
- SystemManager
- TabBar
- TabBar (Spark)
- TabNavigator
- TabStopFormat
- Text
- Text Layout Framework (TLF)
- TextArea
- TextArea (Spark)
- TextBox
- TextConverter
- TextEvent
- TextFlow
- TextFlowUtil
- TextFormat
- TextGraphic
- TextInput
- TextInput (Spark)
- TextLayoutFormat
- TextView
- Themes
- TileLayout
- TileList
- TileOrientation
- Timer
- TitleWindow
- TitleWindow (Spark)
- TLF
- ToggleButton (Spark)
- ToggleButtonBar
- ToolTip
- Transition
- Tree
- TruncationOptions
- UIComponent
- UIFTETextField
- Updater
- URLLoader
- URLRequest
- URLUtil
- URLVariables
- ValidationResultEvent
- Validator
- Validators
- VBox
- VDividedBox
- Vector
- VerticalLayout
- VerticalLayout (Spark)
- VGroup (Spark)
- Video
- VideoDisplay
- VideoElement
- VideoElement (Spark)
- VideoEvent
- VideoPlayer (Spark)
- VideoPlayerScrubBar
- ViewStack
- VScrollBar (Spark)
- VSlider
- VSlider (Spark)
- XML
- XMLList
- XMLListCollection
- ZipCodeValidator
- ZipCodeValidatorDomainType
- Zoom
-
Articles
- December 2010
- November 2010
- October 2010
- September 2010
- August 2010
- July 2010
- June 2010
- May 2010
- April 2010
- March 2010
- February 2010
- January 2010
- December 2009
- November 2009
- October 2009
- September 2009
- August 2009
- July 2009
- June 2009
- May 2009
- April 2009
- March 2009
- February 2009
- January 2009
- December 2008
- November 2008
- October 2008
- September 2008
- August 2008
- July 2008
- June 2008
- May 2008
- April 2008
- March 2008
- February 2008
- January 2008
- December 2007
- November 2007
- October 2007
- September 2007
- August 2007
- July 2007
-
Meta


Hi,Peter deHaan
Thanks for your great post!
I have a another question about this.
I use TextArea component in flex, trigger “Ctrl + Enter” event to newline(use this to send messege in my project), but more empty newline in IE(it’s ok in Firefox or trigger ‘Shift+Enter’),how can i solve this problem?
Thank you very much!!!
Code like below
if(evt.ctrlKey == true && evt.keyCode == Keyboard.ENTER) { ... }hi dis is manish workin in teknopoint multimedia thanks for givin the source of this code…i was trying to disable the enter key by using ifocus manager bt everythin invain..ur code help me out in dis thanks….
How can I disable backspace, left arrow and right arrow keys ?
Can arrow keys disable? I do not know how to do this.
PEFRECT! This solves half of my problem… Care to share if you have a way to prevent someone from doing a copy/paste of text with line feeds in it? Solve that and I’ll be home free!
manovotny,
The code is a bit rough, but does the following work for you?
<?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical" verticalAlign="middle" backgroundColor="white"> <mx:Script> <![CDATA[ private function textArea_textInput(evt:TextEvent):void { if (evt.text == "\\n") { evt.preventDefault(); } } private function textArea_change(evt:Event):void { textArea.text = textArea.text.replace(/\\n|\\r/ig, ""); } ]]> </mx:Script> <mx:TextArea id="textArea" text="The quick brown fox jumped over the lazy dog." verticalScrollPolicy="on" width="100%" height="100%" textInput="textArea_textInput(event);" change="textArea_change(event);" /> </mx:Application>Peter
hey guys,
i want to prevent linefeed using ENTER key rather i want to apply line feed using SHIFT + ENTER key. How do i do that?
any hint?
thanks in advance
hey guys,
sorry to bother you
looks like i found a workaround for that
just used a keylistener as said by jexchan
textInput="if(event.text.indexOf('\\n')!=-1)event.preventDefault();"come on … it is one line code
Hi Peter,
If you can help me – I am working on a chat application – On Enter I want to send the text and on Shift + Enter I want to insert a line feed in the text area where the sender types message. The solution above inserts a linefeed after the whole text, does not break it into multiple lines.
Thanks
Thanks! Having all three event handlers did the trick!
Hi Guys,
In my textarea control, when I press ctrl + b or ctrl + q or any key with ctrl (control) key. It enters a square character.
How can I prevent this to be entered. I mean if somebody presses ctrl key with any other key, No new character should be entered in textarea.
Please help,
jaswant
When I try to do the same thing with a Sparks TextArea in Flex 4 beta 2, the textInput event tag is missing.
Is this normal?
I can listen for the event in AS, but not with a MXML tag..
Try it: add a s:TextArea block, and see if you can a textInput event attribute…
@Dimitri,
The MX/Halo and Spark controls are completely different components. They don’t always have the same APIs and/or functionality. For the Spark TextArea, you may need to listen for a different event (like
changingor something).Peter
Thank you for your answer. But the inputText event is listed in the doc for both TextInput and TextArea Spark components, and I can add an eventListener in AS.
So I really think this is a bug, and I filed a bug report about this:
Yet, if I use the addEventListener method, it works, but the evt.preventDefault(); is not producing effect , i.e the text is modified , in a spark component, but not if I use the halo component.
Should I file a bug report also or do you think this is the correct behaviour of the Spark TextArea? (if so, do you know a workaround to have the same result as your example with a Spark text component).
After further investigation, here is what I found:
With Spark TextArea and TextInput, it seems that you shouldn’t use the textInput event even if you could.
It seems that you should use the changing event instead.
This way, for exemple, you could use event.preventDefault() to cancel the change.
So if you want to use the example of this page with Spark TextArea, replace the textInput tag by a changing tag, and in the handler, the event type is TextOperationEvent instead of TextEvent.
Peter, maybe this should be included in the spark TextArea doc in the textInput item, because it’s not easy to figure it out when transitioning to spark components…
How can I get the new text value when listening for changing events?
In TextArea if user type text without pressing enter key and the text will gose to new line. Now when i request for the textarea htmlText, I can’t get any information which show that now next word is in new line.
Please help.
Bharat
Can arrow keys disable? I do not know how to do this.
Is this the only way? Isn’t there any elegant way of doing this? I’m trying to make a chat window just like YM or Skype has, do you know if there is some source code on that? Uncle G is silent about it…
Here is how you do this in a spark TextArea:
private function onChangingHandler(event:TextOperationEvent):void {
if(event.operation is SplitParagraphOperation)
event.preventDefault();
}