I have one function for the number input box come with + and - button on the sides, and copy the code in my shopify theme which I use. But that function only show one time. But I need those apply to all the product offers.
(function ($) {
$.fn.bootstrapNumber = function (options) {
var settings = $.extend({
upClass: 'default',
downClass: 'default',
center: true
}, options);
return this.each(function (e) {
var self = $(this);
var clone = self.clone();
var min = self.attr('min');
var max = self.attr('max');
function setText(n) {
if ((min && n < min) || (max && n > max)) {
return false;
}
clone.focus().val(n);
return true;
}
var group = $("<div class='input-group'></div>");
var down = $("<button type='button'>-</button>").attr('class', 'btn btn-' + settings.downClass).click(function () {
setText(parseInt(clone.val()) - 1);
});
var up = $("<button type='button'>+</button>").attr('class', 'btn btn-' + settings.upClass).click(function () {
setText(parseInt(clone.val()) + 1);
});
$("<span class='input-group-btn'></span>").append(down).appendTo(group);
clone.appendTo(group);
if (clone) {
clone.css('text-align', 'center');
}
$("<span class='input-group-btn'></span>").append(up).appendTo(group);
// remove spins from original
clone.prop('type', 'text').keydown(function (e) {
if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
(e.keyCode == 65 && e.ctrlKey === true) ||
(e.keyCode >= 35 && e.keyCode <= 39)) {
return;
}
if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
e.preventDefault();
}
var c = String.fromCharCode(e.which);
var n = parseInt(clone.val() + c);
//if ((min && n < min) || (max && n > max)) {
// e.preventDefault();
//}
});
clone.prop('type', 'text').blur(function (e) {
var c = String.fromCharCode(e.which);
var n = parseInt(clone.val() + c);
if ((min && n < min)) {
setText(min);
}
else if (max && n > max) {
setText(max);
}
});
self.replaceWith(group);
});
};
}(jQuery));
How do you initialise the function ?
Your problem certainly lies there...
Because it works using this:
$('input').bootstrapNumber();
See my Fiddle that includes your exact unmodified script.
Related
I been trying to create validation function for input to allow only numeric with two decimal point And max value 99999999.99.
This is what I have tried so far but doesn't seems to be working.
$('#TXTCOST').keypress(function (event) {
if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
event.preventDefault();
}
var input = $(this).val();
if ((input.indexOf('.') != -1) && (input.substring(input.indexOf('.')).length > 2)) {
event.preventDefault();
}
var arr = input.split('.');
if (arr.length == 1 && parseFloat(arr[0]) >= 99999999) {
event.preventDefault();
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="TXTCOST"/>
My example below uses a simple regex check for 1-8 digits number with optional 0-2 decimal points:
Edit: Now the code prevents the entry of wrong value. This is done in 2 stages
On key press, make a backup of the current input value then limit user input to allowed keys
Validate current input then revert back to the old value if the new value is invalid.
let allowed_keys = [8, 46, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 190];
let my_regex = /^([0-9]{0,8})(\.{1,1}[0-9]{0,2})?$/;
let old_val;
let x = $('#TXTCOST').on('keydown', function (event) {
let input_value = $(this).val().toString();
old_val = input_value;
let found_dots = input_value.match(/\./g) || [];
let split_input_value = input_value.split('.');
let prevent_default = false;
// console.log('value = ' + $(this).val());
let tests = [];
tests.push(() => {
return allowed_keys.includes(event.which);
});
tests.push(() => {
return (event.which !== 190) || ((event.which === 190) && (input_value.length > 0) && (found_dots.length === 0))
});
tests.forEach(function (test, index) {
if (test() === false) {
event.preventDefault();
}
});
}).on('input', function (event) {
let input_value = $(this).val().toString();
let tests = [];
tests.push(() => {
if (my_regex.test(input_value)) {
return true;
} else {
return false;
}
});
tests.forEach((test, index) => {
if (test() === false) {
$(this).val(old_val)
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="TXTCOST"/>
try like this.
$('#TXTCOST').keypress(function (event) {
if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
event.preventDefault();
}
else{
var input = $(this).val();
if ((input.indexOf('.') != -1) && (input.substring(input.indexOf('.')).length > 2)) {
event.preventDefault();
}
var arr = (input+String.fromCharCode(event.keyCode)).split('.');
if (arr.length == 1 && parseFloat(arr[0]) > 99999999) {
event.preventDefault();
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="TXTCOST"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="TXTCOST"/>
$('#TXTCOST').keypress(function (event) {
if ((event.which != 46 || $this.val().indexOf('.') != -1) &&
((event.which < 48 || event.which > 57) &&
(event.which != 0 && event.which != 8))) {
event.preventDefault();
}
var input = $(this).val();
if ((input.indexOf('.') != -1) && (input.substring(input.indexOf('.')).length > 2)) {
event.preventDefault();
}
var arr = input.split('.');
if (arr.length == 1 && parseFloat(arr[0]) >= 99999999) {
event.preventDefault();
}
});
try this
Is there available binding to format an input value from 123456789 to 123,456,789. The binding should work on every keypress and validate the value if it is a valid number. I found this solution but it is not formatting on keypress.
I ended up creating custom binding. It only works on IE10 and above for the usage of event input.
Here's the code. See fiddle here.
String.prototype.countOccurence = function(char){
return (this).split(char).length - 1;
}
$.fn.selectRange = function(start, end){
if(end === undefined)
end = start;
return this.each(function() {
if("selectionStart" in this){
this.selectionStart = start;
this.selectionEnd = end;
} else if(this.setSelectionRange)
this.setSelectionRange(start, end);
else if(this.createTextRange){
var range = this.createTextRange();
range.collapse(true);
range.moveEnd("character", end);
range.moveStart("character", start);
range.select();
}
});
};
ko.helper = {};
ko.helper['toNumber'] = function (value, limit){
limit = limit || 10;
var num = Number((value || "").toString().replace(/[^0-9]/gi, "").substring(0, limit));
return num;
}
ko.bindingHandlers['formatNumber'] = {
init: function(element, valueAccessor, allBindings){
var value = valueAccessor();
var limit = allBindings.get("limit") || 10; //billion
var position = 0;
var navigationKeys = [33, 34, 35, 36, 37, 38, 39, 40, 9];
var isBackSpace = false;
var oldLengthValue = (value() || "").toString().length;
function isKeyControls(e){
if(e.ctrlKey && (e.keyCode == 67 || e.keyCode == 86 || e.keyCode == 65)){
return true;
}
if(e.shiftKey && (e.keyCode == 37 || e.keyCode == 39)){
return true;
}
return false;
}
$(element).on("keyup", function(e) {
if(this.selectionStart == this.value.length)
return;
if(isKeyControls(e) || e.shiftKey){
return;
}
var navigation = (e.keyCode == 37
? -1
: e.keyCode == 39
? 1
: 0);
var customSelectionStart = this.selectionStart; // + navigation;
//customSelectionStart = customSelectionStart
var positionMinusOne = customSelectionStart == 0
? -1
: customSelectionStart;
positionMinusOne = positionMinusOne + (positionMinusOne == -1 ? 0 : navigation);
var previousCharacter = positionMinusOne == -1
? ""
: this.value.substring(customSelectionStart - 1, customSelectionStart);
if(previousCharacter == ","){
$(this).selectRange(customSelectionStart +
(isBackSpace ? -1 : 0));
}
var currentCommaOccurence = this.value.countOccurence(",");
var commaValue = oldLengthValue > currentCommaOccurence ? -1
: oldLengthValue < currentCommaOccurence ? 1
: 0;
if(commaValue != 0){
$(this).selectRange(customSelectionStart +
commaValue);
}
oldLengthValue = this.value.countOccurence(",");
});
$(element).on("keydown", function (e) {
if (isKeyControls(e)) {
return;
}
var navigation = (e.keyCode == 37
? -1
: e.keyCode == 39
? 1
: 0);
var customSelectionStart = this.selectionStart + navigation;
//customSelectionStart = customSelectionStart
var positionMinusOne = customSelectionStart == 0
? -1
: customSelectionStart;
positionMinusOne = positionMinusOne + (positionMinusOne == -1 ? 0 : navigation);
var previousCharacter = positionMinusOne == -1
? ""
: this.value.substring(customSelectionStart - 1, customSelectionStart);
if(previousCharacter == ",")
$(this).selectRange(customSelectionStart);
isBackSpace = e.keyCode == 8;
if(isBackSpace)
return;
//Navigation
if(navigationKeys.some(function(key) {
return key == e.keyCode;
}))
return;
//Other Keys
var isNumber = (e.keyCode >= 48 && e.keyCode <= 57) || (e.keyCode >= 96 && e.keyCode <= 105);
var isLimit = (limit + parseInt(limit / 3)) == this.value.length;
if(!(isNumber)
|| isLimit){
e.preventDefault();
return;
}
});
$(element).on("input", function(e, a, b, c) {
console.log(this.selectionStart, this.selectionEnd);
var convertedValue = ko.helper.toNumber(this.value, limit);
var formatted = convertedValue
? ko.helper.toNumber(this.value, limit).toLocaleString()
: "";
position = this.selectionStart == this.value.length
? formatted.length
: this.selectionStart;
value(convertedValue || "");
this.value = formatted;
$(this).selectRange(position);
});
ko.utils.domNodeDisposal.addDisposeCallback(element, function() {
$(element).off();
});
ko.bindingHandlers["formatNumber"].update(element, valueAccessor, allBindings);
},
update: function(element, valueAccessor, allBindings){
var value = valueAccessor();
var limit = allBindings.get("limit") || 10; //billion
var convertedValue = ko.helper.toNumber(value(), limit);
var formatted = convertedValue
? ko.helper.toNumber(value(), limit).toLocaleString()
: "";
element.value = formatted;
}
};
I have a text box that will only show half of the text inputted, unless the text box is a bigger size. Before I type, the cursor is half way showing, when I'm typing, it is normal, then after I type, it goes back to only half way showing. The text box is attached to Java Script that makes it so the inputted amount automatically turns into a dollar amount, would that affect it?
JavaScript:
$(document).ready(function () {
$("input[type=text].currenciesOnly").live('keydown', currenciesOnly)
.live('blur', function () {
$(this).formatCurrency();
});
});
// JavaScript I wrote to limit what types of input are allowed to be keyed into a textbox
var allowedSpecialCharKeyCodes = [46, 8, 37, 39, 35, 36, 9];
var numberKeyCodes = [44, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105];
var commaKeyCode = [188];
var decimalKeyCode = [190, 110];
function numbersOnly(event) {
var legalKeyCode = (!event.shiftKey && !event.ctrlKey && !event.altKey) && (jQuery.inArray(event.keyCode, allowedSpecialCharKeyCodes) >= 0 || jQuery.inArray(event.keyCode, numberKeyCodes) >= 0);
if (legalKeyCode === false) event.preventDefault();
}
function numbersAndCommasOnly(event) {
var legalKeyCode = (!event.shiftKey && !event.ctrlKey && !event.altKey) && (jQuery.inArray(event.keyCode, allowedSpecialCharKeyCodes) >= 0 || jQuery.inArray(event.keyCode, numberKeyCodes) >= 0 || jQuery.inArray(event.keyCode, commaKeyCode) >= 0);
if (legalKeyCode === false) event.preventDefault();
}
function decimalsOnly(event) {
var legalKeyCode = (!event.shiftKey && !event.ctrlKey && !event.altKey) && (jQuery.inArray(event.keyCode, allowedSpecialCharKeyCodes) >= 0 || jQuery.inArray(event.keyCode, numberKeyCodes) >= 0 || jQuery.inArray(event.keyCode, commaKeyCode) >= 0 || jQuery.inArray(event.keyCode, decimalKeyCode) >= 0);
if (legalKeyCode === false) event.preventDefault();
}
function currenciesOnly(event) {
var legalKeyCode = (!event.shiftKey && !event.ctrlKey && !event.altKey) && (jQuery.inArray(event.keyCode, allowedSpecialCharKeyCodes) >= 0 || jQuery.inArray(event.keyCode, numberKeyCodes) >= 0 || jQuery.inArray(event.keyCode, commaKeyCode) >= 0 || jQuery.inArray(event.keyCode, decimalKeyCode) >= 0);
// Allow for $
if (!legalKeyCode && event.shiftKey && event.keyCode == 52) legalKeyCode = true;
if (legalKeyCode === false) event.preventDefault();
}
// jQuery formatCurrency plugin... see http://code.google.com/p/jquery-formatcurrency/
(function ($) {
$.formatCurrency = {};
$.formatCurrency.regions = [];
$.formatCurrency.regions[""] = {
symbol: "$",
positiveFormat: "%s%n",
negativeFormat: "(%s%n)",
decimalSymbol: ".",
digitGroupSymbol: ",",
groupDigits: true
};
$.fn.formatCurrency = function (destination, settings) {
if (arguments.length == 1 && typeof destination !== "string") {
settings = destination;
destination = false;
}
var defaults = {
name: "formatCurrency",
colorize: false,
region: "",
global: true,
roundToDecimalPlace: 2,
eventOnDecimalsEntered: false
};
defaults = $.extend(defaults, $.formatCurrency.regions[""]);
settings = $.extend(defaults, settings);
if (settings.region.length > 0) {
settings = $.extend(settings, getRegionOrCulture(settings.region));
}
settings.regex = generateRegex(settings);
return this.each(function () {
$this = $(this);
var num = "0";
num = $this[$this.is("input, select, textarea") ? "val" : "html"]();
if (num.search("\\(") >= 0) {
num = "-" + num;
}
if (num === "" || (num === "-" && settings.roundToDecimalPlace === -1)) {
return;
}
if (isNaN(num)) {
num = num.replace(settings.regex, "");
if (num === "" || (num === "-" && settings.roundToDecimalPlace === -1)) {
return;
}
if (settings.decimalSymbol != ".") {
num = num.replace(settings.decimalSymbol, ".");
}
if (isNaN(num)) {
num = "0";
}
}
var numParts = String(num).split(".");
var isPositive = (num == Math.abs(num));
var hasDecimals = (numParts.length > 1);
var decimals = (hasDecimals ? numParts[1].toString() : "0");
var originalDecimals = decimals;
num = Math.abs(numParts[0]);
num = isNaN(num) ? 0 : num;
if (settings.roundToDecimalPlace >= 0) {
decimals = parseFloat("1." + decimals);
decimals = decimals.toFixed(settings.roundToDecimalPlace);
if (decimals.substring(0, 1) == "2") {
num = Number(num) + 1;
}
decimals = decimals.substring(2);
}
num = String(num);
if (settings.groupDigits) {
for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3) ;
i++) {
num = num.substring(0, num.length - (4 * i + 3)) + settings.digitGroupSymbol + num.substring(num.length - (4 * i + 3));
}
}
if ((hasDecimals && settings.roundToDecimalPlace == -1) || settings.roundToDecimalPlace > 0) {
num += settings.decimalSymbol + decimals;
}
var format = isPositive ? settings.positiveFormat : settings.negativeFormat;
var money = format.replace(/%s/g, settings.symbol);
money = money.replace(/%n/g, num);
var $destination = $([]);
if (!destination) {
$destination = $this;
} else {
$destination = $(destination);
}
$destination[$destination.is("input, select, textarea") ? "val" : "html"](money);
if (hasDecimals && settings.eventOnDecimalsEntered && originalDecimals.length > settings.roundToDecimalPlace) {
$destination.trigger("decimalsEntered", originalDecimals);
}
if (settings.colorize) {
$destination.css("color", isPositive ? "black" : "red");
}
});
};
$.fn.toNumber = function (settings) {
var defaults = $.extend({
name: "toNumber",
region: "",
global: true
}, $.formatCurrency.regions[""]);
settings = jQuery.extend(defaults, settings);
if (settings.region.length > 0) {
settings = $.extend(settings, getRegionOrCulture(settings.region));
}
settings.regex = generateRegex(settings);
return this.each(function () {
var method = $(this).is("input, select, textarea") ? "val" : "html";
$(this)[method]($(this)[method]().replace("(", "(-").replace(settings.regex, ""));
});
};
$.fn.asNumber = function (settings) {
var defaults = $.extend({
name: "asNumber",
region: "",
parse: true,
parseType: "Float",
global: true
}, $.formatCurrency.regions[""]);
settings = jQuery.extend(defaults, settings);
if (settings.region.length > 0) {
settings = $.extend(settings, getRegionOrCulture(settings.region));
}
settings.regex = generateRegex(settings);
settings.parseType = validateParseType(settings.parseType);
var method = $(this).is("input, select, textarea") ? "val" : "html";
var num = $(this)[method]();
num = num ? num : "";
num = num.replace("(", "(-");
num = num.replace(settings.regex, "");
if (!settings.parse) {
return num;
}
if (num.length === 0) {
num = "0";
}
if (settings.decimalSymbol != ".") {
num = num.replace(settings.decimalSymbol, ".");
}
return window["parse" + settings.parseType](num);
};
function getRegionOrCulture(region) {
var regionInfo = $.formatCurrency.regions[region];
if (regionInfo) {
return regionInfo;
} else {
if (/(\w+)-(\w+)/g.test(region)) {
var culture = region.replace(/(\w+)-(\w+)/g, "$1");
return $.formatCurrency.regions[culture];
}
}
return null;
}
function validateParseType(parseType) {
switch (parseType.toLowerCase()) {
case "int":
return "Int";
case "float":
return "Float";
default:
throw "invalid parseType";
}
}
function generateRegex(settings) {
if (settings.symbol === "") {
return new RegExp("[^\\d" + settings.decimalSymbol + "-]", "g");
} else {
var symbol = settings.symbol.replace("$", "\\$").replace(".", "\\.");
return new RegExp(symbol + "|[^\\d" + settings.decimalSymbol + "-]", "g");
}
}
})(jQuery);
Textbox:
<input type="text" class="currenciesOnly" />
Code from free open source site
With help from #Eyal and #LeoFarmer somewhere within bootstrap, the line-height was affecting it. So I set line-height to normal in the css for the textbox:
.currenciesOnly {
line-height: normal;
}
I have a condition to allow user to input only 2 decimal points number and restrict the alphabets and other characters. I used the following function:
function isNumberKeyOnlyWithDecimalFormat(event,value,id){
var val = value;
if (event.shiftKey === true) {
event.preventDefault();
}
if ((event.keyCode >= 48 && event.keyCode <= 57) ||
(event.keyCode >= 96 && event.keyCode <= 105) ||
event.keyCode == 8 ||
event.keyCode == 9 ||
event.keyCode == 37 ||
event.keyCode == 39 ||
event.keyCode == 46 ||
event.keyCode == 190) {
} else {
event.preventDefault();
}
if(val.indexOf('.') !== -1 && event.keyCode == 190){
event.preventDefault();
}
if ((pointPos = $('#'+id).val().indexOf('.')) >= 0){
$('#'+id).attr("maxLength", pointPos+3);
}
else
$('#'+id).removeAttr("maxLength");
}
It is working fine while first time adding. But it restricts the if i want to edit the digits if it has already 2 decimal place. Can anyone help with this?
Try this. It will check the value each time the focus is gone from the input field, but you can use any event you like. It will parse the value as a float, and then round it to 2 decimal points.
Here is the fiddle: http://jsfiddle.net/sAp9D/
HTML:
<input type="text" id="the_id" />
JavaScript:
var input_field = document.getElementById('the_id');
input_field.addEventListener('change', function() {
var v = parseFloat(this.value);
if (isNaN(v)) {
this.value = '';
} else {
this.value = v.toFixed(2);
}
});
Your question is very hard to understand but if you want to check that a string has only 2 decimals then you can just do this
if( value.match(/\./g).length === 2 ) {
// Number has 2 decimals eg. 1.2.3
} else {
// Number is incorrect eg. 1.2.3.4
}
or if you want 1.2 then
if( value.match(/\./g).length === 1 ) {
// Code....
}
I use the following
// This function will only allow digits
function numericFormat( fld , e , extraStrCheck )
{
var sep = 0;
var key = '';
var i = j = 0;
var len = len2 = 0;
var strCheck = '0123456789';
if ( extraStrCheck )
strCheck += extraStrCheck;
var aux = aux2 = '';
var whichCode = (window.Event) ? e.which : e.keyCode;
if (whichCode == 13) return true; // Enter
if (whichCode == 8) return true; // Backspace
if (whichCode == 0) return true; // Null
if (whichCode == 9) return true; // Tab
key = String.fromCharCode(whichCode); // Get key value from key code
if ( strCheck.indexOf(key) == -1 ) return false; // Not a valid key
var x = new String(fld.value);
if ( key == '.' )
{
var exp = /\./;
var a = x.search(exp);
if ( a != -1 ) return false;
}
}
// samer code on change or on blur event
function allow2decimal(obj){
var v = parseFloat($(obj).val());
if (isNaN(v)) {
$(obj).value = '';
} else {
newVal = v.toFixed(2);
if(newVal >= 100){
$(obj).val( 100 );
}else{
$(obj).val(newVal);
}
}
}
//usage
<input
onkeypress="return numericFormat( this , event , '.');"
onchange="allow2decimal(this)"
value="0.1"
id="factory_silk" name="factory_silk" />
<html>
<head>
<script type="text/javascript">
function NumAndTwoDecimals(e, field) {
var val = field.value;
var re = /^([0-9]+[\.]?[0-9]?[0-9]?|[0-9]+)$/g;
var re1 = /^([0-9]+[\.]?[0-9]?[0-9]?|[0-9]+)/g;
if (re.test(val)) {
}
else {
val = re1.exec(val);
if (val) {
field.value = val[0];
}
else {
field.value = "";
}
}
}
</script>
</head>
<body>
<input type="text" name="text" onkeyup="NumAndTwoDecimals(event , this);">
</body>
</html>
$('.number').keypress(function(evt){
var str = $(this).val();
var index = str.indexOf('.');
if(index==-1){index=0;}else{index= index+1;}
var extrapoint = str.indexOf('.',index);
if(extrapoint>0){$(this).val(str.slice(0,-1));}
var charCode = (evt.which) ? evt.which : event.keyCode;
if(charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
var validNumber = new RegExp(/^\d*\.?\d*$/);
var lastValid = $(this).val();
if (validNumber.test($(this).val()))
{
lastValid = $(this).val();
}
else
{
$(this).val(lastValid);
}
});
I'm validating text-boxes such that they can contain letters,numbers, and these special characters only: ` , - . ' ~
I'm using the Jquery 'key-down' event for this. If the user enters an invalid character,I prevent it from showing up in the textbox.
For the enabling just the tilde, and disabling the other special characters, I'm supposed to detect if the shift key is held down. I've used a Boolean variable for this.
Problem is it's allowing the other special characters like !, $, to be typed in.It isn't going inside the isShiftPressed == true condition in ValidateKeyDown . I had put an alert inside it, which didn't execute.
So this is my code:
$.fn.ValidateKeyDown = function () {
return this.each(function () {
$(this).keydown(function (e) {
if (e.shiftKey) {
isShiftPressed = true;
return;
}
else if (isShiftPressed == false) {
var n = e.keyCode;
if (!((n == 8) // backspace
|| (n == 9) // Tab
|| (n == 46) // delete
|| (n >= 35 && n <= 40) // arrow keys/home/end
|| (n >= 65 && n <= 90) // alphabets
|| (n >= 48 && n <= 57) // numbers on keyboard
|| (n >= 96 && n <= 105) // number on keypad
|| (n == 109) //(- on Num keys)
|| (n == 189) || (n == 190) || (n == 222) || (n == 192) //hypen,period,apostrophe,backtick
)
) {
e.preventDefault(); // Prevent character input
return false;
}
}
else if (isShiftPressed == true) {
var n = e.keyCode;
if (n != 192) {
e.preventDefault(); // Prevent character input
return false;
}
}
return true;
});
});
};
$.fn.ValidateKeyUp = function () {
return this.each(function () {
$(this).keyup(function (e) {
if (e.shiftKey) {
isShiftPressed = false;
}
});
});
};
I noticed that e.shiftKey only returns true on key up and hence isShiftPressed is always false. Try this instead
$.fn.ValidateInput = function () {
return this.each(function () {
$(this).keydown(function (e) {
var n = e.keyCode;
if (n == 16) {
isShiftPressed = true;
return;
}
if (!isShiftPressed) {
if (!((n == 8) // backspace
|| (n == 9) // Tab
|| (n == 46) // delete
|| (n >= 35 && n <= 40) // arrow keys/home/end
|| (n >= 65 && n <= 90) // alphabets
|| (n >= 48 && n <= 57) // numbers on keyboard
|| (n >= 96 && n <= 105) // number on keypad
|| (n == 109) //(- on Num keys)
|| (n == 189) || (n == 190) || (n == 222) || (n == 192) //hypen,period,apostrophe,backtick
)) {
e.preventDefault(); // Prevent character input
return false;
}
}
else if (isShiftPressed) {
if (n != 192) {
e.preventDefault(); // Prevent character input
return false;
}
}
return true;
})
.keyup(function (e) {
if (e.keyCode == 16) {
isShiftPressed = false;
}
});
});
};
Note: I also combined ValidateKeyup and ValidateKeydown, but that shouldn't matter.
e.shiftKey itself tells you whether shift is pressed so you could directly use that. You don't need a separate variable to track that.
$.fn.ValidateKeyDown = function () {
return this.each(function () {
if (!e.shiftKey) {
...
}
else {
...
}
}