no 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/>
<input type="text" class="altnum" id="alt" placeholder="alt num"></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("css class is:"+cssClass);
    if(cssClass === 'numonly') {
        regex = liveNoFormatNumberRegex;
    } else if(cssClass === 'telonly') {
        regex = liveOnlyPhoneNumberCharsRegex;
    } else if(cssClass === 'moneyonly') {
        regex = liveOnlyCurrencyCharsRegex;
    }
    $(this).on('input',function() {
        if(foundSpecialChars()) {
            return;
        }
        else {
            var str = $(this).val();
            console.log("str is:"+str);
            $(this).val($(this).val().replace(regex,''));
            
        }
    });
});

$('input.altnum').each(function() {
    $(this).on('keydown',function(event) {
        var liveNoFormatNumberRegex = new RegExp("\\D","g");
        var str = event.which || event.keyCode || event.charCode;
        var strVal = String.fromCharCode(str);
        console.log("str is:"+strVal);
        var matches = liveNoFormatNumberRegex.test(strVal);
        console.log(matches);
        console.log(foundSpecialChars(event));
        if(specialChars(event)) {
            return;
        }
        if(matches) {
            event.preventDefault();
            return false;
        }
        else {
            return;
        }
        
    });
               
 });

var specialChars = function(event) {
    var key = event.which || event.keyCode || event.charCode;
		if(key == 8 || key === 16 || key === 36 || key == 46 || key == 9) {
			return true;
		}
		else {
			return false;
		}
}

function foundSpecialChars(event) {
		var key = event.which || event.keyCode || event.charCode;
		if(key == 8 || key === 16 || key === 36 ||...