Hello guys,
in this post I’ll show you how to restrict users to input only a numbers in given input field.
It’s very simple solution that uses only a JavaScript / jquery -input only numbers.
jquery – input only numbers
<script> $(document).ready(function() { $("#txtboxToFilter").keydown(function (e) { if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 || (e.keyCode == 65 && e.ctrlKey === true) || (e.keyCode == 67 && e.ctrlKey === true) || (e.keyCode == 88 && e.ctrlKey === true) || (e.keyCode >= 35 && e.keyCode <= 39)) { return; } if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) { e.preventDefault(); } }); }); </script>
Ok, it’s very easy to understand to all.
First, we have to bind the element, so when the key is pressed in the given field, the jquery – input only numbers script, checks the keycode. And if the keycode is valid, the script prints it in the field.
I just allow and some more keys, lets see:
if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
This allows the backspace, delete, tab, escape, enter and . in the jquery – input only numbers script.
(e.keyCode == 65 && e.ctrlKey === true) ||
This allows the CTR+A
(e.keyCode == 67 && e.ctrlKey === true) ||
This allows the CTR+C
(e.keyCode == 88 && e.ctrlKey === true) ||
This allows the CTR+X
(e.keyCode >= 35 && e.keyCode <= 39))
This allows the home, end, left, right buttons
This is it. Enjoy this jquery – input only numbers script 🙂