Filtering Non-Numeric Characters In A Textbox Using Javascript

<html>
<head>

<script type=”text/javascript”>
var shiftOn = false;
var ctrlOn = false;
var altOn = false;
var focusedValue = “0”;

function validateNumeric(obj)
{
if (obj.value.length == 0)
{
obj.value = focusedValue;
return false;
}
else if (obj.value.indexOf(“-“) > 0)
{
obj.value = focusedValue;
return false;
}
else
{
for (var i = 0; i 47) && (keynum 95) && (keynum < 106))) //Numeric
{
switch(keynum)
{
case 8: //Backspace
case 9: //Tab
case 35: //End
case 36: //Home
case 37: //Left Arrow
case 39: //Right Arrow
case 46: //Delete
return true;

case 13: //Enter
case 27: //Esc
obj.blur();
return true;

case 16: //Shift
shiftOn = true;
return true;

case 17: //Ctrl
ctrlOn = true;
return true;

case 18: //Alt
altOn = true;
return false;

case 109: //Minus sign
case 189: //Minus sign
if (obj.value.indexOf(“-“) != -1)
{
return false;
}
else
{
return true;
}

default:
return false;
}
}

return true;
}

function handleKeyUp(e)
{
var keynum;

if (window.event != null) //IE
{
keynum = e.keyCode;
}
else if (e.which != null) //Other
{
keynum = e.which;
}

switch(keynum)
{
case 16: //Shift
shiftOn = false;
break;

case 17: //Ctrl
ctrlOn = false;
break;

case 18: //Alt
altOn = false;
break;
}
}

function handleFocus(obj)
{
focusedValue = obj.value;
obj.select();
}

function handleBlur(obj)
{
validateNumeric(obj);
obj.value = obj.value;
}
</script>

</head>
<body onload=”myText.focus()”>
<input id=”myText” type=”text” onkeydown=”return handleKeyDown(event, this)” onkeyup=”handleKeyUp(event)” onfocus=”handleFocus(this)”
onblur=”handleBlur(this)” /><br />
<br />
<input id=”Text1″ type=”text” />
</body>
</html>

Advertisements