将文本字段输入限制为仅限数字 [英] Limit Textfield Input to digits only
问题描述
我搜索了Google,但是我能找到的所有解决方案都非常复杂和漫长。我需要的是限制我只对数字进行的调查中的文本字段的输入。什么是最快最干净的方法?
(我使用HTML 4.01 strict和ECMAScript)
<
最快:
< input type =textonkeyup =this.value = this.value.replace(/ \D / g,'')>
这不会阻止人们用鼠标粘贴东西,因此onchange和onclick可能
最干净的(或者至少干干净净的做法):
function forceNumeric(){
this.value = this.value.replace(/ \D / g,'');
$ b $ p
$ b如果您使用的是JS框架,请给出所有仅用于数字的输入一个指示事实的类( class =numeric或类似的东西),并添加forceNumeric作为 keyup ,更改的回调。和点击键到任何具有该类的输入元素:
$('。numeric').keyup (forceNumeric).change(forceNumeric)。单击(forceNumeric);
如果您使用的是直线JS(我建议不要使用直线JS),请使用 element.addEventListener 或 onkeyup , onchange 和 onclick 。
I've searched Google, but all the solutions I could find were really complicated and long. What I need is to limit the input of a textfield in a survey I'm making to digits only. What is the quickest and cleanest way to do this?
(I'm using HTML 4.01 strict and ECMAScript)
Thanks in advance.
解决方案 The quickest:
<input type="text" onkeyup="this.value = this.value.replace(/\D/g, '')">
That won't stop people from pasting things in with their mouse, so an onchange and onclick are probably desirable, too.
The cleanest (or at least a clean way to do it):
function forceNumeric() {
this.value = this.value.replace(/\D/g, '');
}
If you're using a JS framework, give all your numeral-only inputs a class that indicates the fact (class="numeric" or something like that), and add forceNumeric as a callback for keyup, change, and click to any input element with that class:
$('.numeric').keyup(forceNumeric).change(forceNumeric).click(forceNumeric);
If you're using straight JS (I'd recommend not using straight JS), either use element.addEventListener, or onkeyup, onchange, and onclick.
这篇关于将文本字段输入限制为仅限数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!