Insert Text at specified position of TextInput, TextArea and TextField, etc. in Flex

Editor-128x128 Someone asked me how to insert text into input components such as TextInput and TextArea at a specified position programmatically.

Solution Summery:TextInput and TextArea are warped for the TextField interactive object contained in the package flash.text. TextField class provides the function replaceText() to help us to complete the insertion.

Search-256x256 Demo | DownloadDownload Full Project

ScreenShot:

insert-text

The following is full source code :

<?xml version="1.0" encoding="utf-8"?>
<mx:Application
	xmlns:mx="http://www.adobe.com/2006/mxml"
	layout="absolute" xmlns:mxeffects="com.adobe.ac.mxeffects.*"
	creationComplete="onCreationComplete();">
	<mx:Script>
		<![CDATA[
			import mx.core.mx_internal;
			use namespace mx_internal;

			private var textField:TextField;

			[Bindable]
			private var insertionPointIndex:int;

			private function onCreationComplete():void
			{
				textField = TextField(myText.getTextField());
				textField.addEventListener(MouseEvent.CLICK,onTextFieldClick);
				myText.addEventListener(TextEvent.TEXT_INPUT,onTextAreaTextInput);
				myText.addEventListener(Event.CHANGE,onTextAreaChange);
			}

			private function onTextFieldClick(event:Event):void
			{
				update();
			}

			private function onTextAreaTextInput(event:Event):void
			{
				update();
			}

			private function onTextAreaChange(event:Event):void
			{
				update();
			}

			private function update():void
			{
				insertionPointIndex = textField.caretIndex;
			}

			private function insert():void
			{
				textField.replaceText(insertionPointIndex,insertionPointIndex,insertion.text);
			}
		]]>
	</mx:Script>
	<mx:Panel width="100%" height="100%">
		<mx:TextArea id="myText" width="100%" height="100%" >

		</mx:TextArea>
		<mx:ControlBar>
			<mx:Form>
				<mx:FormItem label="insertion point index">
					<mx:Label text="{insertionPointIndex}"/>
				</mx:FormItem>
			</mx:Form>
			<mx:FormItem label="insertion" direction="horizontal">
				<mx:TextInput id="insertion"/>
				<mx:Button label="insert" click="insert();"/>
			</mx:FormItem>
		</mx:ControlBar>
	</mx:Panel>
</mx:Application>

Enjoy!!

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • DZone
  • Reddit
  • Technorati
  • StumbleUpon
  • Twitter
RSS Enjoy this Post? Subscribe to Ntt.cc

RSS Feed   RSS Feed     Email Feed  Email Feed Follow us Follow us
You can leave a response, or trackback from your own site.

4 Responses to “Insert Text at specified position of TextInput, TextArea and TextField, etc. in Flex”

  1. eBuildy says:

    You can use the simple replaceSelectedText function instead.

    eBuildy, the Web2 builders

  2. Emmad says:

    Thanks a lot man its really works on TextField :)

  3. Ganesh says:

    very vary Thanks

  4. Sam says:

    Thnx a lot for posting it! It works perfect:)

Leave a Reply