AS3 Insert and Delete Characters at TextField CaretIndex Position


/ Published in: ActionScript 3
Save to your folder(s)

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.


Copy this code and paste it in your HTML
  1. // This code assumes you have an input textfield on the stage
  2. // called 'inputTxt' and two movieclips called 'onInsertBtnClick' and 'onBackspaceBtnClick'.
  3. // Here we are just inserting incrementing number as an example.
  4.  
  5. import flash.events.MouseEvent;
  6. import flash.text.TextField;
  7.  
  8. var num:int = 1;
  9.  
  10. insertBtn.addEventListener(MouseEvent.CLICK, onInsertBtnClick);
  11. insertBtn.buttonMode = true;
  12. backspaceBtn.addEventListener(MouseEvent.CLICK, onBackspaceBtnClick);
  13. backspaceBtn.buttonMode = true;
  14.  
  15. function onInsertBtnClick(e:MouseEvent):void {
  16. var charToInsert:String = String(num);
  17. var tf:TextField = inputTxt;
  18. var initialText:String = tf.text;
  19. var ci:int = tf.caretIndex;
  20. var newText:String = initialText.substring(0, ci) + charToInsert + initialText.substring(ci, initialText.length)
  21. tf.text = newText;
  22. tf.setSelection(ci+(charToInsert.length), ci+(charToInsert.length));
  23. num++;
  24. stage.focus = tf;
  25. }
  26.  
  27. function onBackspaceBtnClick(e:MouseEvent):void {
  28. var tf:TextField = inputTxt;
  29. var initialText:String = tf.text;
  30. var ci:int = tf.caretIndex;
  31. if (tf.text != "") {
  32. var newText:String = initialText.substring(0, ci-1) + initialText.substring(ci, initialText.length);
  33. tf.text = newText;
  34. tf.setSelection(ci-1, ci-1);
  35. }
  36. stage.focus = tf;
  37. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.