允许通过数字文本框的按键、按键事件执行某些按键
这是我的代码,它使用 asp.net ajax 客户端库添加事件处理程序
function IsDigit(id) { //short variable,args name for best minification
if ($get(id)) {
var v = function (e) {
var r = /\d/;
if (!r.test(String.fromCharCode(e.keyCode))) e.preventDefault();
}
$addHandlers($get(id), {
keydown: v
});
}
}
$get(ID)
获取带有 id 的控件 $addHandlers
将事件Handlers 添加到控件。这里我将它附加到 ID 为 id 的控件上。这一切都运行良好,文本框只接受数字输入,但问题是当他想要删除所有数字并想要输入一些其他数字时。所以类似 SHFT + HOME 然后删除、Delete 不起作用。请有人能更好地完善代码。 Keydown 也是此类工作的最佳选择 我通过这样做暂时解决了这个问题,但这确实允许意外字符短暂存在,然后将其删除
function IsDigit(id) { //short variable,args name for best minification
if ($get(id)) {
var p = "";
var v = function (e) {
var r = /^\d*$/;
if (r.test(this.value)){p = this.value;} else {this.value=p;}// e.preventDefault();
}
$addHandlers($get(id), {
keyup: v
});
}
}
Here's my code and it uses asp.net ajax client library to add event handlers
function IsDigit(id) { //short variable,args name for best minification
if ($get(id)) {
var v = function (e) {
var r = /\d/;
if (!r.test(String.fromCharCode(e.keyCode))) e.preventDefault();
}
$addHandlers($get(id), {
keydown: v
});
}
}
$get(ID)
gets the control with the id$addHandlers
adds event Handlers to the control. Here i attach it to the control with ID id
. It all works well the textbox accepts only numeric input, but the problem is when he wants to delete all numeric and wants to enter some other numbers. So something like SHFT + HOME and then delete, Delete are not working. Please can someone refine the code better. Also is Keydown optimal for this kind of job
I temporarily solved it by doing this, but this does allow unexpected characters for brief second then removes it
function IsDigit(id) { //short variable,args name for best minification
if ($get(id)) {
var p = "";
var v = function (e) {
var r = /^\d*$/;
if (r.test(this.value)){p = this.value;} else {this.value=p;}// e.preventDefault();
}
$addHandlers($get(id), {
keyup: v
});
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可能会发现验证
onblur
更容易,而不是尝试进行验证onkeydown
/onkeyup
。这样,您就不必担心有人可能会使用各种组合键来选择/删除/重新键入文本,例如 ctrl + 箭头键、ctrl + v 用于粘贴文本、ctrl + a 用于选择全部。您始终可以使用新的 HTML5
来约束输入,然后使用 Modernizr 为不支持新输入类型的浏览器添加事件处理程序代码:
Rather than trying to do your validation
onkeydown
/onkeyup
you might find it easier to validateonblur
. That way you don't have to worry about the various key combinations that someone might use to select / delete / re-type text e.g. ctrl + arrow keys, ctrl + v for pasting text, ctrl + a to select all.You could always use the new HTML5
<input type="number">
to constrain the input, then use Modernizr to add your event handler code for browsers that don't support the new input type: