asdg>> technotes>> handle enter in multiline text fields

Version: Flash MX
Date Added: April 29, 2003

Chat applications typically have a text field into which the user types chat messages. To send a chat message, the user presses a "Send" button or the Enter key. For example:
In Flash, the code that detects the Enter key for a single-line text field might look something like this:
// Method to handle key presses.
ChatRoom.prototype.onKeyDown = function () {
  // If enter was pressed and the 
  // outgoing_txt text field has focus.
  if ((Key.getCode() == Key.ENTER) 
      && (Selection.getFocus() 
          == targetPath(this.room_mc.outgoing_txt))) {

    // Get the input in the outgoing_txt text field.
    var msg = this.room_mc.outgoing_txt.text;

    // Send the input to the server.
    this.chatApp.sendChatMsg(msg);

    // Clear the outgoing_txt text field.
    room_mc.outgoing_txt.text = "";
  }
}
The above code works well for single-line text fields, but not for multiline text fields. In multiline fields, the onKeyDown() event is triggered before Flash actually adds the character that was typed to the text field. Hence, when the above code is used and Enter is pressed in a multiline text field Flash will:
  • send the chat message to the server
  • clear the text field's contents
  • add a blank line character to the text field
To prevent the blank line from being added to the multiline text field, we must move the code that clears the outgoing_txt text field to an onKeyUp() handler, as follows:
// Method to handle key presses.
ChatRoom.prototype.onKeyDown = function () {
  // If enter was pressed and the 
  // outgoing_txt text field has focus.
  if ((Key.getCode() == Key.ENTER) 
      && (Selection.getFocus() 
          == targetPath(this.room_mc.outgoing_txt))) {

    // Get the input in the outgoing_txt text field.
    var msg = this.room_mc.outgoing_txt.text;

    // Send the input to the server.
    this.chatApp.sendChatMsg(msg);
  }
}

// Method to handle key releases.
ChatRoom.prototype.onKeyUp = function () {
  // If enter was released and the 
  // outgoing_txt text field has focus.
  if ((Key.getCode() == Key.ENTER) 
      && (Selection.getFocus() 
          == targetPath(this.room_mc.outgoing_txt))) {

    // Clear the outgoing_txt text field.
    room_mc.outgoing_txt.text = "";
  }
}