Got a problem which is really bothering me for almost 5 hours now, I'm not really familiar with JS and I have to admit that I really need help:
So I got a form element where I can enter some text. Only numbers and some controls should be allowed here, so 0 - 9 and left-arrow, right-arrow, del and backspace. Everything else shouldn't even appear. My code almost works, I can't enter anything else than these, EXCEPT when Capslock is active and I press 5 - then it enters %. In my despair, I tried some very strange constructions (you'll see it below) and tortured google with my requests, found dozens of threads about it (one even here on stackoverflow), but no solution.
Now my little testform looks like this:
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(document).ready(function() {
$("#test").keypress(function(e) {
var code = e.keyCode ? e.keyCode : e.which;
console.log("keyCode: " + code + " | Shift: " + e.shiftKey + " | charCode:" + e.charCode);
if(e.shiftKey){
return false;
}
if(code == 20) {
return false;
}
if(e.charCode == 0) {
return true;
}
if(code != 8){
if(code != 46){
if(code != 37 && e.charCode == 0){
if(code != 39 && e.charCode == 0) {
if(code <= 48 || code >= 58){
return false;
}
}
}
}
}
});
});
</script>
</head>
<body>
<label>Input:<input type="text" id="test"></label>
</body>
</html>
I can't use onKeyDown here, because then % would return keyCode 53 which would prevent 5 from being entered too. I can't use the "numeric" field either because I want to support older browsers too which don't know this attribute.
So short:
- all numbers allowed
- del allowed
- left/right arrow allowed
- backspace allowed
- everything else forbidden
Hope anyone here knows a solution for this one. As I said, I'm not really familiar with JavaScript and got a bit trouble solving this.^^
jsfiddle here, modified the original form a little bit for better display.