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 ...
随机推荐
- JSP 简单标签extends SimpleTagSupport
1.控制JSP页面某一部分内容是否执行 public void doTag() this.getJspBody().invoke(null);执行 空白,不执行 2.控制JSP页面内容重复执行 pac ...
- Oracle三种排名函数使用
1) SELECT s.*,Row_Number() OVER (partition by c_name ORDER BY grade desc) rank FROM score s 2) SELEC ...
- 使用URLOS 五分钟安装rTorrent (轻量级优秀BT/PT客户端)
rTorrent是一个非常简洁.优秀.非常轻量的BT客户端,它使用ncurses库以C++编写,将 rTorrent 用在安装有 GNU Screen 和 Secure Shell 的低端系统上作为远 ...
- Java 使用第三方推送 -- 极光推送
官网链接 : https://www.jiguang.cn/ 注册完成登录后,点击创建应用 这里不细说 Java后端的整合如下: 添加maven依赖的包 <dependency> < ...
- eclipse 导入项目出现的问题汇总
Unbound classpath variable: 'TOMCAT_HOME' in project XXX Problem 翻译:未绑定的类路径变量:项目XXX中的“TOMCAT_HOME” 解 ...
- elasticsearch的cross_fields查询
1.most_fields 这种方式搜索也存在某些问题 它不能使用 operator 或 minimum_should_match 参数来降低次相关结果造成的长尾效应. 2.词 peter 和 smi ...
- NIO入门
NIO:Non-blocking IO,即非阻塞式IO. 标准的IO基于字节流和字符流进行操作. 而NIO基于通道(Channel)和缓冲区(Buffer)进行操作,数据总是从Channel读取到Bu ...
- 设计模式:职责链模式(Chain of Responsibility)
去年参加校招要到长沙来,这个对于我来说不是特别喜欢(但又必须的来,谁叫咱不是985.211的娃呢),但是对于某些人来说就是福音了.大四还有课,而且学校抓的比较严,所以对于那些想翘课的人来说这个是最好不 ...
- Luogu P5354 [Ynoi2017]由乃的OJ
题目 这题以前叫睡觉困难综合征. 首先我们需要知道起床困难综合征怎么做. 大概就是先用一个全\(0\)和全\(1\)的变量跑一遍处理出每一位\(1\)和\(0\)最后会变成什么. 然后高位贪心:如果当 ...
- JAVA break、continue和return的区别
控制跳转:continue和break的区别,以为return Continue在循环中使用,一般在for中使用 Break:跳出单重循环,常和switch搭配使用. 效果区别 Break的结果如下: ...