/ Published in: ActionScript 3
This code gets the current caretIndex in the textfield and then inserts the specified string at that point. The caretIndex position is then updated using setSelection, ready for the next insertion. This was developed to be used with an on-screen keyboard (for entering text into a textfield when the user is in fullscreen mode). The backspace button is intended to function in the same manner as pressing the delete key on your keyboard.
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
// This code assumes you have an input textfield on the stage // called 'inputTxt' and two movieclips called 'onInsertBtnClick' and 'onBackspaceBtnClick'. // Here we are just inserting incrementing number as an example. import flash.events.MouseEvent; import flash.text.TextField; var num:int = 1; insertBtn.addEventListener(MouseEvent.CLICK, onInsertBtnClick); insertBtn.buttonMode = true; backspaceBtn.addEventListener(MouseEvent.CLICK, onBackspaceBtnClick); backspaceBtn.buttonMode = true; function onInsertBtnClick(e:MouseEvent):void { var charToInsert:String = String(num); var tf:TextField = inputTxt; var initialText:String = tf.text; var ci:int = tf.caretIndex; var newText:String = initialText.substring(0, ci) + charToInsert + initialText.substring(ci, initialText.length) tf.text = newText; tf.setSelection(ci+(charToInsert.length), ci+(charToInsert.length)); num++; stage.focus = tf; } function onBackspaceBtnClick(e:MouseEvent):void { var tf:TextField = inputTxt; var initialText:String = tf.text; var ci:int = tf.caretIndex; if (tf.text != "") { var newText:String = initialText.substring(0, ci-1) + initialText.substring(ci, initialText.length); tf.text = newText; tf.setSelection(ci-1, ci-1); } stage.focus = tf; }