Search code examples
javascripthtmlcssinput

HTML Number Input: Only Allow Arrow Buttons


Here is what I mean:

Input Image

Is it possible to only allow input via clicking the arrow buttons, and NOT from actually typing?

Ie: I could not type in "11", but if I click the up arrow 11 times then it will go to 11?

Here is my input field right now:

        <input type="number" min="00" max ="99" id="timer02_min" 
        maxlength="2" value="00">

Is there some native way of doing this? Or should I look more into buttons and some styling?


Solution

  • Use event.preventDefault() in keydown event;

    // no keyboard
    document.getElementById("timer02_min").addEventListener("keydown", e => e.preventDefault());
    
    // allow up/down keyboard cursor buttons
    document.getElementById("timer02_min2").addEventListener("keydown", e => e.keyCode != 38 && e.keyCode != 40 && e.preventDefault());
    no keyboard:
    <input type="number" min="00" max ="99" id="timer02_min" 
            maxlength="2" value="00">
    <br>
    with up/down cursor keys:
    <input type="number" min="00" max ="99" id="timer02_min2" 
            maxlength="2" value="00">