Last active
August 29, 2015 14:11
-
-
Save andrewspear/193cb331531a05bd8bc0 to your computer and use it in GitHub Desktop.
Using a number input field is great for basic HTML5 browser validation (but this only kicks in on submit) and smartphones will usually offer up a number-only keyboard which is nice. However this script enhances the HTML5 number input field so it's easier to use: 1) only numbers can be typed in the box, 2) you can't type more characters than the …
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Prevent non-numeric entries on number inputs | |
$("input[type=number]").keydown(function (e) { | |
// Allow: backspace, delete, tab, escape, enter and . | |
if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 || | |
// Allow: Ctrl+A | |
(e.keyCode == 65 && e.ctrlKey === true) || | |
// Allow: home, end, left, right, down, up | |
(e.keyCode >= 35 && e.keyCode <= 40)) { | |
// let it happen | |
return; | |
} | |
// Ensure that it is a number and stop the keypress | |
if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) { | |
e.preventDefault(); | |
} | |
// Check length (if adding this keypress puts it over the limit then prevent it) | |
var value = $(this).val(); | |
var max = $(this).attr('max'); | |
if(value.length+1 > max.length) { | |
e.preventDefault(); | |
} | |
}); | |
// Prevent number field change on scroll | |
$('form').on('focus', 'input[type=number]', function (e) { | |
$(this).on('mousewheel.disableScroll', function (e) { | |
e.preventDefault(); | |
}); | |
}); | |
$('form').on('blur', 'input[type=number]', function (e) { | |
$(this).off('mousewheel.disableScroll'); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment