将文本字段输入限制为仅限数字 [英] Limit Textfield Input to digits only

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

问题描述

我搜索了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屋!

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