Ad

Convert JQuery Into AddEventListener For Keypress Event

I needed to craete an input which only accepts number. For that, I have created an input with type text and only accepts 5 digits of length.

<input id="inputNumber" type="text" maxlength="5">

For accepting only number, I created jquery code like the following.

$("#inputNumber").keypress(function (value) {
// If the letter is not digit then display error and don't type anything
if (value.which != 8 && value.which != 0 && (value.which < 48 || value.which > 57)) {
return false;
}
else {
return true;
}
});

I tried to convert it into AddEventListner for my Type script file but failed. I even tried below method but failed again. How can I resolve this.

Referece: keypress event doesn't log input value first time event is fired

Ad

Answer

If you are looking for js equivalent code that might look like:

const inputNumber = document.querySelector("#inputNumber");

inputNumber.addEventListener("keypress", (event) => {

  if (isNaN(event.key)) {
    event.preventDefault();
    return false;
  } else {
    return true;
  }
});
<input id="inputNumber" type="text" maxlength="5">

I needed to craete an input which only accepts number.

You can use input type="number" instead or simplify validation to !isNaN(event.key)

const inputNumber = document.querySelector("#inputNumber") as HTMLInputElement;

inputNumber.addEventListener("keydown", (event: KeyboardEvent) => {

  if (isNaN(Number(event.key))) {
    event.preventDefault();
    return false;
  } else {
    return true;
  }
});
Ad
source: stackoverflow.com
Ad