0

i have made on textbox which is readonly. I want that when user press a number from keyboard then they are entered in textbox. I have applied onkeyup() event in the text box but it is not working.

<input type="text" id="screen" value="0" onkeyUp="myFunction(event)" readonly=true; >
function myFunction(event){
    if ( event.keycode >= 48 && event.keycode <=57 ) {
        //some code here
    }

}
1
  • Maybe better with <input type="number"> or <input pattern="\d+">? Commented Feb 10, 2014 at 9:49

2 Answers 2

2

First of all, it's keyCode and not keycode, and you can go with something like

window.addEventListener("keyup", function(e) {
    if ( e.keyCode >= 48 && event.keyCode <=57 ) {
            document.getElementById("screen").value += String.fromCharCode(e.keyCode);
        }
}, false);

http://jsfiddle.net/npCBs/

Do note that only the upper number keys will work, and not the num pad.

Sign up to request clarification or add additional context in comments.

2 Comments

Listen to keyCodes between 96 to 105, if clicked, substract 48 from the keyCode and then get the result by String.fromCharCode
which event(keyup,keydown,keypress) should i use so that it works fine on all browser?
0

readonly attribute specifically means that no input is to be accepted by the input that has the readonly attribute.

try adding the onkeyup attribute to body. the tradeoff is that any keyboard event will be captured

<body onkeyUp="myFunction(event)">
...
 <input type="text" id="screen" value="0"  readonly=true; >            
...
</body>

this should call the myFunction everytime user presses a key.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.