1. JavaScript (external) — Block – key
This input uses external JavaScript to prevent minus sign entry. The event listener watches for ‘keydown’ events and blocks specifically the ‘-‘ key or ‘Minus’ key from being entered.
1 2 3 4 5 6 7 8 |
<input type="number" id="jsBlock" placeholder="JS keydown block" /> <script> document.getElementById('jsBlock').addEventListener('keydown', function(e) { if (e.key === '-' || e.key === 'Minus') { e.preventDefault(); } }); </script> |
2. HTML Only — min=”0″
This input uses only HTML attributes to prevent negative numbers. The min=”0″ attribute ensures the number can’t go below zero, though users can still type a minus sign (it will be removed when focus leaves the field).
1 |
<input type="number" min="0" placeholder="HTML min=0 only" /> |
3. Inline JavaScript — onkeydown in HTML
This input uses inline JavaScript to block minus signs immediately on key press. Similar to the first example but implemented directly in the HTML markup rather than through an external script.
1 2 3 4 5 6 |
<input type="number" min="0" onkeydown="if(event.key === '-' || event.key === 'Minus') event.preventDefault();" placeholder="Inline JS block" /> |
4. Block – on Paste Too
This input extends the protection by preventing both typing minus signs AND pasting text that contains minus signs. It checks clipboard data during paste events and blocks if a minus is detected.
1 2 3 4 5 6 7 |
<input type="number" min="0" onkeydown="if(event.key === '-' || event.key === 'Minus') event.preventDefault();" onpaste="let paste = (event.clipboardData || window.clipboardData).getData('text'); if(paste.includes('-')) event.preventDefault();" placeholder="Prevent - on key & paste" /> |