Forum Moderators: open

Message Too Old, No Replies

Allowing only numbers in input field.

         

ocon

11:02 am on Feb 26, 2016 (gmt 0)

10+ Year Member Top Contributors Of The Month



I am having the hardest time preventing anything but numbers from being inserted into an input field.

I'm trying to block any non-number input from any sources including the keyboard, dragging, or pasting. I am also trying to do so without any jQuery.

This is what my current code looks like:

<input type="tel" name="amount" id="amount" value="" maxLength="3" pattern="\d*" placeholder="15" autocomplete="off" title="Amount" />
...
<script>
'use strict';
var $ = function(n){return document.getElementById(n)};
$('amount').onkeypress = $('amount').ondrop = $('amount').onpaste = function(e){
if(e.which < 48 || e.which > 57) return false;};
</script>

It generally works well, but I'm having issues with mobile phones allowing special characters, or any dragging or pasting events.

Fotiman

1:21 pm on Feb 26, 2016 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Have you tried calling e.preventDefault() instead of only returning false?