[英]Add Javascript Keydown event from C# to a textbox
I'm building a set of text boxes from asp.net repeater and trying to add a key down event from C# code to those text boxes to prevent user from entering a specific character ( comma(,)
).我正在从 asp.net repeater 构建一组文本框,并尝试将 C# 代码中的按键事件添加到这些文本框中,以防止用户输入特定字符(
comma(,)
)。 I can't use the text box id itself in Javascript because its built dynamically with diff id's.我不能在 Javascript 中使用文本框 id 本身,因为它是用 diff id 动态构建的。 Now I have no idea how to pass the
e
object to the textbox's keydown event from C#.现在我不知道如何将
e
对象从 C# 传递给文本框的 keydown 事件。
Any suggestion is much appreciated.任何建议都非常感谢。
Code Snippet :代码片段:
TextBox txtTextField = e.Item.FindControl("txtAns_1") as TextBox;
txtTextField.Attributes.Add("keydown", "PreventChars(" + txtTextField +")");
Javascript Javascript
function PreventChars(e) {
var k = String.fromCharCode(e.which);
if (k.match(/,/g))
{
e.preventDefault();
}
};
use ClientID
使用客户端ID
ClientID returns The control ID for HTML markup that is generated by ASP.NET.
ClientID 返回由 ASP.NET 生成的 HTML 标记的控件 ID。
Change Code Snippet to:将代码片段更改为:
TextBox txtTextField = e.Item.FindControl("txtAns_1") as TextBox;
txtTextField.Attributes.Add("keydown", "PreventChars(" + txtTextField.ClientID +")");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.