Forum Moderators: open
'The following is entered in the codebehind
Dim txtQuantity As TextBox = e.Item.Cells(4).FindControl("txtQuantity")
txtQuantity.Attributes.Add("onkeypress", "IsNumeric(" & txtQuantity.ClientID & ",'Integer')")
'this is the javascript function called when the textbox's onkeypress event is fired
function IsNumeric(TextBox,strType)
// check for valid numeric strings
{
if (strType="Decimal")
{
var strValidChars = "0123456789.";
}
else if (strType="Integer")
{
var strValidChars = "0123456789";
}
var strString;
var strChar;
strString=TextBox.value; for (i = 0; i < strString.length; i++)
{
strChar = strString.charAt(i);
if (strValidChars.indexOf(strChar) == -1)
{
TextBox.value = TextBox.value.substring(0, i);
TextBox.value.length = i
event.returnValue = false;
}
}
}
I'm not very proficient in Javascript so I'd appreciate any suggestions.
You could do something like
function isNumber(text){ var goodChars = "0123456789.";[/code] var isNum = true; var char; // loop through the chars in the text you passed in for (var idx = 0; text.length; idx++) { char = text.charAt(i); // if the char isn't in the string of good // characters then exit returning false if (goodChars.indexOf(char) == -1) { return false; } } // if you made it this far then your gold return true; } } Hope that helps.
// pass a reference to the field using:
// onkeypress/onchange/onblur='chkNumeric(this)'
function chkNumeric(obj) {
var val = "";
//split the string every time a non-numeric is found
var vals = obj.value.split(/(\D)/);
for (var i=0;i<vals.length;i++)
//make your leftover characters, all numeric, into a string
val += vals[i];
obj.value = val;
...
}
hth,
g.