Recently I was given an unusual request that I have the most difficult time for addressing, which involves capturing all the displayed characters when entering into a text field. The installation is as follows:
I have a text box that has a maximum length of 10 characters. When a user tries to type more than 10 characters, I need to notify the user that he is printing out of the allowed number of characters.
The simplest solution would be to specify a maxlength of 11, check the length for each keyword and trim to 10 characters, but this solution looks a bit silly. I would prefer to capture the character before keyup and, depending on whether it is a displayable character, present a notification to the user and prevent the default action.
Whitelisting will be problematic as we process a lot of international data.
I played with every combination of keystrokes , keystrokes and keystrokes , reading event.keyCode , an event. charCode and event.which , but I can not find a single combination that would work in all browsers. The best I could do is the following, which works correctly in> = IE6, Chrome5, FF3.6, but does not work in Opera:
NOTE . The following code uses jQuery.
$(function(){
$('#textbox').keypress(function(e){
var $this = $(this);
var key = ('undefined'==typeof e.which?e.keyCode:e.which);
if ($this.val().length==($this.attr('maxlength')||10)) {
switch(key){
case 13:
case 9:
case 27:
case 8:
case 0:
break;
default:
alert('no - '+e.charCode+' - '+e.which+' - '+e.keyCode);
return false;
};
}
});
});
I admit that what I am doing is probably overly designed the solution, but now that I have invested in it, I would like to know about the solution.