const onlyIntegers = () => { const myInput = document.querySelectorAll("input[type=number]"); function keyAllowed(key) { const keys = [8, 9, 13, 16, 17, 18, 19, 20, 27, 46, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 91, 92, 93 ]; if (key && keys.indexOf(key) === -1) return false; else return true; } myInput.forEach(function(element) { element.addEventListener('keypress', function(e) { const key = !isNaN(e.charCode) ? e.charCode : e.keyCode; if (!keyAllowed(key)) e.preventDefault(); }, false); // Disable pasting of non-numbers element.addEventListener('paste', function(e) { const pasteData = e.clipboardData.getData('text/plain'); if (pasteData.match(/[^0-9]/)) e.preventDefault(); }, false); }) }; useEffect(() => { onlyIntegers() }, []); <Input type='number'/>
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter