Javascript - only allow numbers in input field & a character counter

Viewed 852

I have an input field. I want it so that only numbers can be used in the input field.

Below the input field I also want a counter that shows the number of characters currently inside the input field.

HTML:

<input type="text" id="test" onkeypress="return isNumber(event)" />
<p id='demo'></p>

Javascript:

function isNumber(evt) {
    evt = (evt) ? evt : window.event;
    var charCode = (evt.which) ? evt.which : evt.keyCode;
    if (charCode > 31 && (charCode < 48 || charCode > 57)) {
        return false;
    }
    let inputValue = document.getElementById('test').value;
    let inputLength = inputValue.length;
    document.getElementById("demo").innerHTML = inputLength;
    return true;
    }

jsfiddle: http://jsfiddle.net/s831nwej/

It almost works. The problem is that the character counter below the input box is always 1 character less than the total number of characters in the input field. I think there is some quark about the keypress event that I am missing.

3 Answers
Related