Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

When the event's default action is prevented, not only is the input prevented from being added to the TextField, the model for the component is also unchanged.

The JavaScript version of this bead works similarly to the JavaScript PasswordInputBead where you set things up in the strand setter and listen for the appropriate event, a keypress event in this case:

Code Block

// javascript strand setter
    value.addEventListener('keypress',goog.bind(this.validateInput, this));

Unlike ActionScript, JavaScript input elements (prior to HTML 5) do not have any way to restrict input characters, so you have to do that yourself, which is done in the validateInput() event handler:

Code Block

// javascript
  var code = event.charCode;
  
  // backspace or delete
  if (event.keyCode == 8 || event.keyCode == 46) return;
  
  // tab or return/enter
  if (event.keyCode == 9 || event.keyCode == 13) return;
  
  // left or right cursor arrow
  if (event.keyCode == 37 || event.keyCode == 39) return;
  
  var key = String.fromCharCode( code );

  var regex = /[0-9]|\./;
  if( !regex.test(key) ) {
    event.returnValue = false;
    if(event.preventDefault) event.preventDefault();
    return;
  }
  var cursorStart = event.target.selectionStart;
  var cursorEnd   = event.target.selectionEnd;
  var left = event.target.value.substring(0,cursorStart);
  var right = event.target.value.substr(cursorEnd);
  var complete = left + key + right;
  if (isNaN(complete)) {
    event.returnValue = false;
    if(event.preventDefault) event.preventDefault();
  }

The top portion of the function allows special keys to go through unaltered (backspace, tab, return, delete, and arrow keys). The next test determines if the character is '0' through '9' or the period. If the character fails that test, the event is prevented (same as ActionScript). If the character is valid, it is inserted into the input string and that assemblage is tested. If the string now fails a numeric test (isNaN() can take either a number or a string) the event is also prevented.

Using the Bead

Updating the Manifest and Library

...