I have this input text:
010 141 474 010 141 474
I want to press the above numbers in order that is presented, one by one. I use a flag to allow only one number at time, but it doesn’t work correct. In the code that is depict I can press both numbers firt, but I want first 0, second 1, third 0 etc… And what about with duplicates numbers? I duplicate the code? Also I thought to check if a button is onkeyup but nothing. Any help? Thanks in advance. My code:
function keyPressed(event){
var code;
var isKeyRepeating = false;
if(window.event){ //IE
code = event.keyCode;
}
else{ //other browsers
code = event.which;
}
if (code == 48 || code == 96){ //both keycodes for the same number
document.onkeypress("0");
isKeyRepeating = true;
}
if (code == 49 || code == 97){
document.onkeypress("1");
isKeyRepeating = true;
}
else {
event.preventDefault();
isKeyRepeating = false;
}
}
input field:
<input style="border-style: inset" size="90" type="text" name="key" id="txtboxToFilter" onkeypress="javascript:keyPressed(event);"/>
Your question is most confusing. Typing one character at a time is completely trivial, unless you specifically want to prevent holding keys down. As such, I’m not sure what you even want.
If you want the user to only be able to type the characters in the correct order, this will work for you:
There is another answer which uses a similar function, but the critical difference is that it uses an
onkeydownhandler, which produces different results. One needs to understand thatonkeydowndeals with a single key pressed, whileonkeypressdeals with a single character typed. For example, if you type uppercaseA, there are twokeydownevents: one forshift, another fora. There is however only onekeypressevent forA.Even more critical is that one cannot expect all key codes to match with character codes when using
onkeydown. For example, the key codes for numbers are different if typed from the numpad, and the key codes for special characters are completely unreliable. Usingonkeypresshowever, the key codes will match with character codes, if the key represents a visible character.Therefore, the deciding factor between using
onkeydownoronkeypressis whether you wish to detect arbitrary key presses, or visible typed characters.(The following was part of the original answer, while it turned out it was not what the OP wanted, I’m leaving it here for reference).
If you want the user to only be able to type number, this will do it: