TextBox t = new TextBox();
t.addKeyPressHandler(new KeyPressHandler(){
public void onKeyPress(KeyPressEvent event) {
char keyCode = event.getCharCode();
if(!(keyCode > '0' && keyCode <'9') ) {
t.cancelKey();
}
}
});
Similarly, you can limit the number of characters a text box can take
TextBox t = new TextBox();
t.addKeyPressHandler(new KeyPressHandler(){
public void onKeyPress(KeyPressEvent event) {
if(t.getText().length() >= 5 ) {
t.cancelKey();
}
}
});
PS: For the syntax highlight of your code in a post, follow this link http://pleasemakeanote.blogspot.com/2008/06/posting-source-code-in-blogger.html
Thanks, simple and elegant solution. I would just change to
ReplyDeleteif(!(keyCode >= '0' && keyCode <= '9')) { // filter out 0-9
if (!((keyCode == '\b') || (keyCode == '%') || (keyCode == '\'') || (keyCode == '.'))) // filter out backspace, del, and left and right arrows
quantity.cancelKey();
}
to allow 0 and 9, and to allow back, delete, and arrow keys