Skip to content

Instantly share code, notes, and snippets.

@jaapie
Last active August 29, 2015 14:16
Show Gist options
  • Save jaapie/e30f0a0da47aad10778f to your computer and use it in GitHub Desktop.
Save jaapie/e30f0a0da47aad10778f to your computer and use it in GitHub Desktop.
Allows only number keys, enter and full stop to be entered into an input[type=number] and ensures the format is that of a floating point number
(function() {
"use strict";
var els = document.querySelectorAll('input[type=number]');
function makeKeypressEventHandler() {
return function (e) {
var keyCode = e.which || e.keyCode;
if ((keyCode >= 48 && keyCode <= 57) ||
keyCode == 13 || keyCode == 46) {
// Key is OK, but need to make sure that the number adheres to
// the correct format (a digit optionally followed by a
// decimal point and more digits)
if ((this.value + String.fromCharCode(keyCode)).search(/^\d+(\.\d*)?$/) === 0) {
return;
} else {
// console.log(String.fromCharCode(keyCode) + ", (" + keyCode + ")");
e.preventDefault();
}
} else {
// console.log(String.fromCharCode(keyCode) + ", (" + keyCode + ")");
e.preventDefault();
}
};
}
for (var i = 0; i < els.length; i++) {
els[i].addEventListener('keypress', makeKeypressEventHandler());
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment