Last Thursday I was told that in my application, the field was allowing the entry of numbers from the main keyboard but not the numeric keypad. I discovered that the behavior of the dojo combobox differs from that of the core controls. In this post, I will explain the usage of the keypress event in general, and then explain how to use it with a dojo combobox.
Before I begin, I have to laugh at the irony of this new Stack Overflow question (http://stackoverflow.com/questions/33680515/how-to-prevent-special-characters-input-into-edit-box) about this very subject that appeared a few hours after working on this. Amazingly no one had answered it by the time I saw it, and of course it was fresh on my mind, so I answered it with what I was already going to put in this new blog post.
Keyboard Events
There are three key events that you can use. The onkeypress, and the okeydown, and the onkeyup. As the name implies these are keyboard events. In XPages you can assign client and/or server code to each. I would strongly caution for performance reasons against doing anything serverside that is more complicated then setting a scoped variable. The code that we want to use to limit certain keys is all clientside javascript.
Usage in an Edit Control
This code shown here will only allow numbers and the backspace key. In XPages, if applied to a core control, this also allows the numeric keyboard to work even though it uses different keycodes. The
keycodes for the numeric keyboard are 96-105. For an edit box the only event you need is the onKeyPress.
keycodes for the numeric keyboard are 96-105. For an edit box the only event you need is the onKeyPress.
Usage in a Dojo Combobox
One of the nice features of the dojo combobox is that you can choose from the list or type in a value. You also get built in type ahead. The key events work differently in two specific ways though. If you just use the onkeypress event, then if the user types really fast they can bypass the event and type an unwanted character. These are the types of things the quality assurance people are happy to point out to you. The way to prevent this behavior is to put the code in both the onkeydown and onkeyup events.
How to selectively include or exclude any key
My example above on specifically includes numbers, your needs may differ. You can use http://keycode.info/ to easily figure out any keycode. Modify the code below to meet your specific requirements. This example only allows letters, numbers, backspace, and delete.
var keyCode = event.keyCode;
if((keyCode >= 48 && keyCode <= 57) || (keyCode >= 65 && keyCode <= 90)|| keyCode == 8 || keyCode == 46){
event.returnValue = true;
}else{
event.returnValue = false;
}
if((keyCode >= 48 && keyCode <= 57) || (keyCode >= 65 && keyCode <= 90)|| keyCode == 8 || keyCode == 46){
event.returnValue = true;
}else{
event.returnValue = false;
}
No comments:
Post a Comment