Input type number to only accept integers using addeventListner

I want html input to only accept 1 to 999 numbers with max length of 3 characters of the input.
But my code is failing for decimal number. For example: 1.2 is accepted by the input.I don’t want decimal or float number. Please help.
HTML

<input id="measuredNumber" type="number" min="1" max="999" />

JavaScript:

const measuredNumber= document.getElementById("measuredNumber") as HTMLInputElement;
        measuredNumber.addEventListener("input", (e) => {
            e.preventDefault();
            const input = e.currentTarget as HTMLInputElement;
            if (input.value.length === 0 && input.value === "") {
                input.value = "";
            }
            else if (input.value.length > 3) {
                input.value = input.value.slice(0, 3);
            }
            else if (+input.value < 1) {
                input.value = "1";
            }
            else if (input.value === "000") {
                input.value = "1";
            }
        });

128 thoughts on “Input type number to only accept integers using addeventListner”

Leave a Comment