2

I have this input

<input name="minSalary" value="49800" style="width: 45px" maxlength="5" id="numbersonly"></td>

and this script

document.getElementById('numbersonly').onkeydown = function(e) {
    var key = e.keyCode ? e.keyCode : e.which;
    if ( isNaN( String.fromCharCode(key) ) ) return false;
}

Right now the input only responds when numbers are pressed. I would also like to respond to backspace and delete.

1 Answer 1

3

you can also allow the keycodes 8 (backspace) and 46 (delete) to achieve this

document.getElementById('numbersonly').onkeydown = function(e) {
    var key = e.keyCode ? e.keyCode : e.which;
    if ( isNaN( String.fromCharCode(key) ) && key != 8 && key != 46 ) return false;
}

Maybe you should also allow 37 and 39 for navigation with the arrow keys inside the input

Here is a list of all keycodes available: http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes

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

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.