Skip to content

Instantly share code, notes, and snippets.

@rwoodr
Created February 28, 2015 00:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rwoodr/ebf66a6766e07ca0dc8f to your computer and use it in GitHub Desktop.
Save rwoodr/ebf66a6766e07ca0dc8f to your computer and use it in GitHub Desktop.
jQuery to allow only integers or floats in text input
//Select text inputs in container
//Highlight input text on focus
//Allow certain keys
$("#container-id input:text")
.focus(function() {$(this).select();})
.mouseup(function(e) {e.preventDefault();})
.keydown(function (e) {
//Allow: backspace, delete, tab, escape, enter, (decimal) and (period)
//Only one '.' allowed
//Adding data-nofloat='1' to element will disabled '.' for that input
var allowArray = [46, 8, 9, 27, 13, 110, 190];
if ($(this).data('nofloat') || $(this).val().indexOf('.') > -1) {
//has data-nofloat='true' or already has a '.' in value
//Remove last two codes (decimal and period)
allowArray = allowArray.slice(0, 4);
}
if ($.inArray(e.keyCode, allowArray) !== -1 ||
//Allow Ctrl+A (select all)
(e.keyCode == 65 && e.ctrlKey === true) ||
//Allow home, end, left, right
(e.keyCode >= 35 && e.keyCode <= 39)) {
//Do nothing
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();
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment