jQuery:限制文本框仅“数字"输入的最佳方法是什么? (允许小数点) [英] jQuery: what is the best way to restrict "number"-only input for textboxes? (allow decimal points)
问题描述
限制文本框仅数字"输入的最佳方法是什么?
我正在寻找一种允许小数点的东西.
我看到了很多例子.但尚未决定使用哪个.
从Praveen Jeganathan更新
没有更多的插件,jQuery已实现了v1.7中添加的自己的jQuery.isNumeric()
.
参见: https://stackoverflow.com/a/20186188/66767
更新
有一个新的非常简单的解决方案:
它允许您在文本
<input>
上使用任何类型的输入过滤器, 包括各种数值过滤器.这将正确处理 复制+粘贴,拖动+拖放,键盘快捷键,上下文菜单操作, 不可键入的键以及所有键盘布局.
请参见此答案或自己尝试一下 jquery.numeric 插件.
$(document).ready(function(){
$(".numeric").numeric();
});
此外,这也适用于textareas!
但是,请注意,按Ctrl + A,复制+粘贴"(通过上下文菜单)和拖动+拖放"将不能正常工作.
HTML 5
随着对HTML 5标准的更广泛支持,我们可以对input
元素使用pattern
属性和number
类型来限制仅数字输入.在某些浏览器(尤其是Google Chrome)中,它还可以限制粘贴非数字内容. 此处. >
What is the best way to restrict "number"-only input for textboxes?
I am looking for something that allows decimal points.
I see a lot of examples. But have yet to decide which one to use.
Update from Praveen Jeganathan
No more plugins, jQuery has implemented its own jQuery.isNumeric()
added in v1.7.
See: https://stackoverflow.com/a/20186188/66767
Update
There is a new and very simple solution for this:
It allows you to use any kind of input filter on a text
<input>
, including various numeric filters. This will correctly handle Copy+Paste, Drag+Drop, keyboard shortcuts, context menu operations, non-typeable keys, and all keyboard layouts.
See this answer or try it yourself on JSFiddle.
jquery.numeric plugin
I've successfully implemented many forms with the jquery.numeric plugin.
$(document).ready(function(){
$(".numeric").numeric();
});
Moreover this works with textareas also!
However, note that Ctrl+A, Copy+Paste (via context menu) and Drag+Drop will not work as expected.
HTML 5
With wider support for the HTML 5 standard, we can use pattern
attribute and number
type for input
elements to restrict number only input. In some browsers (notably Google Chrome), it works to restrict pasting non-numeric content as well. More information about number
and other newer input types is available here.
这篇关于jQuery:限制文本框仅“数字"输入的最佳方法是什么? (允许小数点)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!