Restricting Input in HTML Textboxes to Numeric Values
Ok, here’s a fairly basic one – how to force a textbox to accept only numeric input. Somebody asked me this today on a support call so I did a few quick lookups online and found the solutions listed rather unsatisfying. The main problem with most of the examples I could dig up was that they only include numeric values, but that provides a rather lame user experience. You need to still allow basic operational keys for a textbox – navigation keys, backspace and delete, tab/shift tab and the Enter key - to work or else the textbox will feel very different than a standard text box.
Yes there are plug-ins that allow masked input easily enough but most are fixed width which is difficult to do with plain number input. So I took a few minutes to write a small reusable plug-in that handles this scenario. Imagine you have a couple of textboxes on a form like this:
- <div class="containercontent">
- <div class="label">Enter a number:</div>
- <input type="text" name="txtNumber1" id="txtNumber1" value="" class="numberinput" />
- <div class="label">Enter a number:</div>
- <input type="text" name="txtNumber2" id="txtNumber2" value="" class="numberinput" />
- </div>
and you want to restrict input to numbers. Here’s a small .forceNumeric() jQuery plug-in that does what I like to see in this case:
[Updated thanks to Elijah Manor for a couple of small tweaks for additional keys to check for]
- <script type="text/javascript">
- $(document).ready(function () {
- $(".numberinput").forceNumeric();
- });
- // forceNumeric() plug-in implementation
- jQuery.fn.forceNumeric = function () {
- return this.each(function () {
- $(this).keydown(function (e) {
- var key = e.which || e.keyCode;
- if (!e.shiftKey && !e.altKey && !e.ctrlKey &&
- // numbers
- key >= 48 && key <= 57 ||
- // Numeric keypad
- key >= 96 && key <= 105 ||
- // comma, period and minus, . on keypad
- key == 190 || key == 188 || key == 109 || key == 110 ||
- // Backspace and Tab and Enter
- key == 8 || key == 9 || key == 13 ||
- // Home and End
- key == 35 || key == 36 ||
- // left and right arrows
- key == 37 || key == 39 ||
- // Del and Ins
- key == 46 || key == 45)
- return true;
- return false;
- });
- });
- }
- </script>
With the plug-in in place in your page or an external .js file you can now simply use a selector to apply it:
$(".numberinput").forceNumeric();
The plug-in basically goes through each selected element and hooks up a keydown() event handler. When a key is pressed the handler is fired and the keyCode of the event object is sent. Recall that jQuery normalizes the JavaScript Event object between browsers. The code basically white-lists a few key codes and rejects all others. It returns true to indicate the keypress is to go through or false to eat the keystroke and not process it which effectively removes it.
Simple and low tech, and it works without too much change of typical text box behavior.
AND OTHER WAYS
1.
$(".numericOnly").keypress(function (e) {if (String.fromCharCode(e.keyCode).match(/[^0-9]/g)) return false;
});
2.
jQuery('.plan_eff').keyup(function () {
this.value = this.value.replace(/[^1-9\.]/g,'');
});
<input name="number" onkeyup="if (/\D/g.test(this.value)) this.value = this.value.replace(/\D/g,'')">
- 3.
// Allow: backspace, delete, tab, escape, enter, ctrl+A and .
if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
// Allow: Ctrl+A
(e.keyCode == 65 && e.ctrlKey === true) ||
// Allow: home, end, left, right
(e.keyCode >= 35 && e.keyCode <= 39)) {
// let it happen, don't do anything
return;
}
var charValue = String.fromCharCode(e.keyCode)
, valid = /^[0-9]+$/.test(charValue);
if (!valid) {
e.preventDefault();
}
Restricting Input in HTML Textboxes to Numeric Values的更多相关文章
- [D3] Convert Dates to Numeric Values with Time Scales in D3 v4
Mapping abstract values to visual representations is what data visualization is all about, and that’ ...
- Classifying with k-Nearest Neighbors(k近邻)
终于要开始写自己的第一篇博客啦,真有点小激动(手足无措 =.=!).因为最近正在琢磨机器学习,第一篇博客就从学的第一个算法开始:k-nearest neighbors algorithm即k近邻算法. ...
- ArcEngine控制台应用程序
转自wbaolong原文 ArcEngine控制台应用程序 控制台应用程序相比其他应用程序,更加简单,简化了许多冗余,可以让我们更加关注于本质的东西. 现在让我们看一看ArcGIS Engine的控制 ...
- Matlab一个错误引发的血案:??? Error using ==> str2num Requires string or character array input.
Matlab总遇到一些神奇的问题,让人摸不着头脑.昨天编写程序的时候遇到一个让我十分火大的问题,也是自己的matlab基础不好吧. 先描述一下问题,再GUI界面有个listbox,Tag属性是’lis ...
- swift语言点评六-Numbers and Basic Values
Topics Logical Values struct Bool A value type whose instances are either true or false. Numeric Val ...
- 【转载】algorithm、numeric、functional
reference url:http://www.cplusplus.com/reference/algorithm reference url:https://blog.csdn.net/Swust ...
- http2协议翻译(转)
超文本传输协议版本 2 IETF HTTP2草案(draft-ietf-httpbis-http2-13) 摘要 本规范描述了一种优化的超文本传输协议(HTTP).HTTP/2通过引进报头字段压缩以及 ...
- Oracle Database 11g express edition
commands : show sys connect sys as sysdba or connect system as sysdba logout or disc clear screen or ...
- Python教程大纲
缘起:最近想在部门推Python语言,写这个blog主要就是个教程大纲,之前先列出一些资源:Python历史:http://www.docin.com/p-53019548.html ...
随机推荐
- 【D3D12学习手记】CPU/GPU Synchronization
由于有两个并行运行的处理器(CPU和GPU),会出现许多同步问题.假设我们有一些资源R存储了我们希望绘制的某些几何体的位置. 此外,假设CPU更新R的数据以存储位置p1,然后将引用R的绘图命令C添加到 ...
- 【转】最新版zookeeper配置看这一篇就够了
[From]https://blog.csdn.net/yydriver/article/details/81107954 版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载 ...
- Linux :linux磁盘分区(普通分区2T以内),安装免安装版mysql(tar.gz)
1.磁盘分区: 1 以root身份登录 查看磁盘信息(自行选择需要使用的磁盘,此处只需要了解信息) fdisk –l 创建新硬盘 fdisk /dev/vdb (决定使用哪个磁盘) 输入n回车,再输入 ...
- 【Python开发】python使用urllib2抓取防爬取链接
前几天刚看完<Linux/Unix设计思想>,真是一本不错的书,推荐想提高自己代码质量的童鞋看一下,里面经常提到要以小为美,一个程序做好一件事,短小精悍,因此我也按照这种思想来写pytho ...
- 谈一谈 Normalize.css
Normalize.css是一种CSS reset的替代方案.它在默认的HTML元素样式上提供了跨浏览器的高度一致性.相比于传统的CSS reset,Normalize.css是一种现代的.为HTML ...
- 蓝鲸 修改主机名重装后初始化不了cmdb安装不了job + 数据采集流程
1.表象:在部署蓝鲸JOB过程中需要进行RabbitMQ的安装,数据初始化,激活步骤,此问题多发生在此过程 [ root@rbtnodel install)# ./bkcec initdata rab ...
- 最短meeting路线(树的直径)--牛客第四场(meeting)
题意: 给你一棵树,树上有些点是有人的,问你选一个点,最短的(最远的那个人的距离)是多少. 思路: 其实就是树的直径,两遍dfs,dfs第二遍的时候遇到人就更新直径就行了,ans是/2,奇数的话+1. ...
- spark教程(10)-sparkSQL
sparkSQL 的由来 我们知道最初的计算框架叫 mapreduce,他的缺点是计算速度慢,还有一个就是代码比较麻烦,所以有了 hive: hive 是把类 sql 的语句转换成 mapreduce ...
- 基于VS搭建OpenCV环境
OpenCV OpenCV的全称是Open Source Computer Vision Library,是一个跨平台的计算机视觉库.OpenCV是由英特尔公司发起并参与开发,以BSD许可证授权发行, ...
- 多表表与表关系 增删改查 admin
今日内容 多表表与表关系 增删改查表数据 admin 多表操作 表与表关系 默认指向主键 可能是隐藏主键 djamgo1.1默认级联(models. SET NULL解除级联) 一对一 先建立少的一方 ...