I have a textbox where I’m using jQuery to limit the input to numeric characters only. The issue I’m having is that when the 4 digit code starts with a 0, it gets deleted from the textbox on focusout or when another number is entered. It’s an mvc3 application and the datatype is string. How do I keep the leading zero from being deleted? Is there something I’m not noticing in my jQuery code? This also applies if there are multiple leading zeros for example, “0025”.
$('#selector').bind('keyup paste', function (e) {
if (checkArrowKeyEntry(e)) {
var ob = $(this);
if (e.type == 'paste') {
setTimeout(function () {
myFuncion(ob);
}, 1);
} else {
myFuncion(ob);
}
}
});
function myFuncion(ob) {
ob.val(numericInputOnly(ob.val()));
}
function checkArrowKeyEntry(e) {
isNotArrowKey = true;
if (e.keyCode == 37 || e.keyCode == 39) { //|| e.keyCode == 8 || e.keyCode == 46) {
// leftarrow, rightarrow, delete, backspace
isNotArrowKey = false;
}
return isNotArrowKey;
}
function numericInputOnly(inputvalue) {
if (!isNaN(parseInt(inputvalue, 10))) {
inputvalue = parseInt(inputvalue, 10);
}
else {
inputvalue = "";
}
inputvalue = inputvalue.toString().replace(/[^0-9]/g, '');
return inputvalue;
}
I suspect there is something wrong in the numericInputOnly function.
You correctly make sure that it always outputs a string (so that the leading 0s do not get trimmed out), but you convert the inputValue to a string too early.
the bug in your code is on the line :
converting to an int will “lose” the trailing 0s.
Try for example with
this will keep only the digits that were typed (all digits including leading 0s) and might correspond to what you need.