Wednesday, April 28, 2010

Suppress specific characters in a GWT Textbox

Some times we need to suppress specific characters in our GWT text box. Suppose you want only numbers to be allowed in your text box then you need to suppress all the alphabets in that text box. This you can do by attaching a key board listener to the text box and the method onKeyPress should do the required processing for suppressing. Below is the code for a text box which allows only numbers.

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

1 comment:

  1. Thanks, simple and elegant solution. I would just change to

    if(!(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

    ReplyDelete