Last active
August 29, 2015 14:16
-
-
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
This file contains 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
(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