tel - money or number only fields js
by Fernando De Leon
HTML
<input type="text" class="telonly" id="tel" placeholder="tel no only"></input><br/>
<input type="text" class="numonly" id="num" placeholder="numbers only"></input><br/>
<input type="text" class="moneyonly" id="money" placeholder="money only"></input><br/>
JavaScript
$('input.telonly, input.numonly, input.moneyonly').each(function() {
var regex,
cssClass = $(this).attr('class');
//var liveOnlyCurrencyCharsRegex = /[^0-9^(^)^$^.^,]/g;
var liveOnlyCurrencyCharsRegex = new RegExp("[^0-9^(^)^$^.^,]","g");
var liveNoFormatNumberRegex = new RegExp("\\D","g");
var liveOnlyPhoneNumberCharsRegex = new RegExp("[^0-9^(^)^\\s]","g");
alert("the cssClass is:"+cssClass);
if(cssClass === 'numonly') {
regex = liveNoFormatNumberRegex;
} else if(cssClass === 'telonly') {
regex = liveOnlyPhoneNumberCharsRegex;
} else if(cssClass === 'moneyonly') {
regex = liveOnlyCurrencyCharsRegex;
}
$(this).on('keydown',function(e) {
if(foundSpecialChars()) {
return;
}
else {
// $(this).val($(this).val().replace(regex,''));
var str = $(this).val();
alert("the str is:"+str+" is there a regex match:"+str.match(regex));
if(str.match(/[0-9]/g)) {
alert("allow to return");
return;
} else {
$(this).val("");
e.preventDefault();
return false;
}
}
});
});
function foundSpecialChars() {
var key = event.which || event.keyCode || event.charCode;
if(key == 8 || key === 16 || key === 36 || key == 46 || key == 9) {
return true;
}
else {
return false;
}
}