Search code examples
javascripthtmlkeypress

Get value of input with keypress and capture key pressed


I am using a keypress event and I want to get the value within the input box after a key has been pressed. I also would like to capture which key has been pressed. In this example I am only allowing the user to enter numbers into the input box (I know there is a number type for inputs). I am using setTimeout to get the value from the input box. Is there a better way to accomplish this? Would this ever fail?

var elTest = document.getElementById('test');
var elResult = document.getElementById('result');

function isNumber(evt, el) {
  evt = (evt) ? evt : window.event;
  var charCode = (evt.which) ? evt.which : evt.keyCode;
  if (charCode > 31 && (charCode < 48 || charCode > 57)) {
    evt.preventDefault();
    return false;
  }
  setTimeout(function () {
    elResult.textContent = el.value;
  }, 0);
  return true;
}

elTest.addEventListener('keypress', function(e) {
  return isNumber(e, this);
});
<input id='test' />
<div id='result'>

</div>


Solution

  • I would go with a combination of keydown and keyup event listeners due to the fact that the keypress event doesn't fire on backspace or delete.

    On keydown, check for number, backspace/delete input and prevent if needed.

    On keyup, update the result output from the input value.

    var elTest = document.getElementById('test');
    var elResult = document.getElementById('result');
    
    function allowInput(evt) {
        var charCode = (evt.which) ? evt.which : evt.keyCode;
        var isNumber = charCode < 58 && charCode > 47;
        var isBackspace = charCode == 8 || charCode == 46;
        return isNumber || isBackspace;
    }
    
    elTest.addEventListener('keydown', function (e) {
        if (!allowInput(e)) {
            e.preventDefault();
            return false;
        }
        return true;
    });
    
    elTest.addEventListener('keyup', function (e) {
        elResult.textContent = this.value;
    });