javascripthtmlangularjs

How to block +,-,e in input type Number?


When I'm giving input type number the letter e and special charecters are also displaying in input field. I want to display only digits. How to block them?

<input type="number">


Solution

  • Try preventing the default behaviour if you don't like the incoming key value:

    document.querySelector(".your_class").addEventListener("keypress", function (evt) {
        if (evt.which != 8 && evt.which != 0 && evt.which < 48 || evt.which > 57)
        {
            evt.preventDefault();
        }
    });
    
    // 0 for null values
    // 8 for backspace 
    // 48-57 for 0-9 numbers
    <input type="number" class="your_class">