how to limit textbox can only input plus number using javascript?

Y

yezanxiong

Hi Everyone,

I am new in asp.net, and i am not quite familar with javascipt. I know how
to use javascript to force textbox's input turn to uppercase, here is the
sample code.

Dim oStrBuilder As System.Text.StringBuilder = New System.Text.StringBuilder
oStrBuilder.Append("<script language='javascript'>")
oStrBuilder.Append("function Upper(e,r) {")
oStrBuilder.Append("if (e.keyCode > 96 && e.keyCode < 123) ")
oStrBuilder.Append(" e.keyCode = e.keyCode - 32; ")
oStrBuilder.Append("}")
oStrBuilder.Append("</script>")
If (Not IsClientScriptBlockRegistered("UPPER")) Then
RegisterClientScriptBlock("UPPER", oStrBuilder.ToString)
End If

But I don't know how to limit textbox can only input plus number? Is that
anyone has the sample code or someone can write it for me?
Thanks a lot.

Yezanxiong
 
B

Brock Allen

But I don't know how to limit textbox can only input plus number?

So you're looking to only allow numbers to be input into the TextBox? If
this is what you're asking, then you can use the CompareValidator control
to do a DataTypeCheck:

<asp:TextBox runat="server" ID="_foo"></asp:TextBox>
<asp:CompareValidator runat="server" ControlToValidate="_foo" Type="Integer"
Operator="DataTypeCheck">* Invalid</asp:CompareValidator>
 
Y

yezanxiong

because I use textbox in the Datagrid, and I don't want to use
CompareValidator, is that another way like using javascript to solve this
problem??
Thanks.

Yezanxiong
 
B

Brock Allen

The CompareValidator does use javascript. Why not use it? If you don't want
to, then you can build your own. The easitest way is to probabaly reeverse
engineer how the CompareValidator does it thing then replicate that. But
then if you're going to do that, then why not use the CompareValidator?
 
J

James [MS-SDK]

Try this code to limit TextBox input to numbers.

function OnKeyDown(obj)
{
if((event.keyCode >= 48 && event.keyCode <=57) || (event.keyCode >= 96 &&
event.keyCode <=105))
{
event.returnValue = true;
}
else
{
event.returnValue = false;
}
}


I call this method using the 'onkeydown' event of the textbox.
<asp:textbox onkeydown="OnKeyDown(this)" runat="server"></asp:textbox>

--
James Johansen, Longhorn SDK
This posting is provided "AS IS" with no warranties, and confers no rights.
Use of included script samples are subject to the terms specified at
http://www.microsoft.com/info/cpyright.htm
--------------------
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top