仅允许在输入字段中键入数字 [英] Only Allow Numbers to be Typed in Input Field

查看:84
本文介绍了仅允许在输入字段中键入数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望此网站上的电话号码字段仅接受数字或数字。我没有编辑HTML代码的权限,所以可以通过定位字段的ID来使用jQuery来完成吗?如果是这样,怎么办呢?

I'd like to have the phone number field on this website only accept numbers or digits. I do not have access to edit the HTML code, so can this be done with jQuery by targeting the field's ID? If so, how can it be done?

我已经在这个网站上尝试了一些建议,到目前为止还没有任何建议。

I've already tried a few suggestions on this site and none have worked so far.

提前感谢您的任何帮助!

Thanks in advance for any assistance!

推荐答案

使用jQuery挂钩到textfield的按键事件。在处理程序中,读取文本字段的值并使用正则表达式替换过滤掉您不想要的所有内容。

Use jQuery to hook into the textfield's keypress event. In the handler, read the textfield's value and filter out everything that you don't want using a regex replace.

更新:未经测试的示例说明:

Update: untested example to illustrate:

jQuery("#myPhonefield").keypress(function(){
    var value = jQuery(this).val();
    value = value.replace(/[^0-9]+/g, '');
    jQuery(this).val(value);
});

这篇关于仅允许在输入字段中键入数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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