Skip to content

Instantly share code, notes, and snippets.

@Jberivera
Last active August 29, 2015 14:14
Show Gist options
  • Select an option

  • Save Jberivera/f4a38a4b4928d15b8e4d to your computer and use it in GitHub Desktop.

Select an option

Save Jberivera/f4a38a4b4928d15b8e4d to your computer and use it in GitHub Desktop.
This function makes that an input field only allows numbers and just one comma, below you'll find the anonymous function version
//this is the functional version of the same code allowing you work with several inputs
var onlyNumbers = function(){
'use strict';
var coma = true,
that = this;
this.addEventListener('keyup', function(e){
var key = e.keyCode,
value = that.value;
if(key == 8 && value.search(/,/) === -1){
coma = true;
}
});
return function(e){
var key = String.fromCharCode(e.keyCode),
regex = /\d/;
if(!regex.test(key)){
if(coma && key == ','){
coma = false;
}else{
e.returnValue = false;
}
}
};
};
//Now you can call onlyNumbers function in all your inputs
var text1 = document.getElementById('soloNum'),
text2 = document.getElementById('soloNum');
text1.addEventListener('keypress', onlyNumbers.call(text1));
text2.addEventListener('keypress', onlyNumbers.call(text2));
//this is the anonymous function version
var soloNumTxt = document.getElementById('soloNum');
soloNumTxt.addEventListener('keypress', function(){
'use strict';
var coma = true;
soloNumTxt.addEventListener('keyup', function(e){
var key = e.keyCode,
value = soloNumTxt.value;
if(key == 8 && value.search(/,/) === -1){
coma = true;
}
});
return function(e){
var key = String.fromCharCode(e.keyCode),
regex = /\d/;
if(!regex.test(key)){
if(coma && key == ','){
coma = false;
}else{
e.returnValue = false;
}
}
};
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment