在asp.net代码中的keypress事件 [英] In asp.net code keypress event

查看:78
本文介绍了在asp.net代码中的keypress事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


我要验证文本框,在文本框中仅输入数字.我需要Asp.net中的代码,但在此按键事件中不可用.
如何获取按键事件?

Hi,
I want validation for text box in a text box enter only digits. I want code in Asp.net but in this keypress event not available.
How to get key press event?

推荐答案

您好

您可以在文件后面的代码中添加按键事件,如下所示

Hi

You add key press event in the code behind file as below

protected void Page_Load(object sender, EventArgs e)
    {
        TextBox1.Attributes.Add("onkeypress", "javascript:return allownumbers(event);");
    }


并在aspx页面中编写如下的Javascript函数


and write the Javascript function as below in the aspx page

function allownumbers(e)
  {
   var key = window.event ? e.keyCode : e.which;
   var keychar = String.fromCharCode(key);
   var reg = new RegExp("[0-9.]")
   if (key == 8)
   {
    keychar = String.fromCharCode(key);
   }
   if (key == 13)
   {
    key=8;
    keychar = String.fromCharCode(key);
   }
   return reg.test(keychar);
  }


尝试一下:

Try this:

<asp:TextBox ID="TextBox1" onkeyup="Page_ClientValidate();" runat="server"></asp:TextBox>
        <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ErrorMessage="Only numeric data allowed."

            Display="Dynamic" ValidationExpression="\d+" ControlToValidate="TextBox1"></asp:RegularExpressionValidator>
        <br />
        <asp:Button ID="Button1" runat="server" Text="Button" />



每次按键时,此代码都会测试输入是否为数字.如果输入不是数字,则显示验证消息.



At each key press, this code tests whether the input is Numeric or not. If input is not numeric, validation message is shown.


这篇关于在asp.net代码中的keypress事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆