简体   繁体   English

通过javascript onkeypress问题在文本框中仅输入数字

[英]Enter only number in text box by javascript onkeypress problem

I have a html text box, onkeypress event will call a function and the function allow to enter only numbers (0-9).我有一个 html 文本框, onkeypress事件将调用一个函数,该函数只允许输入数字 (0-9)。 this is working fine when the user enter by directly.当用户直接输入时,这工作正常。

The problem will come when the user copy and paste some character or String into the text box.当用户将某些字符或字符串复制并粘贴到文本框中时,问题就会出现。 I don't know when should I call that JavaScript function to validate pasted values are Number or Char.我不知道什么时候应该调用该 JavaScript 函数来验证粘贴的值是数字还是字符。

Any idea?任何的想法?

也许您可以尝试使用 onchange 事件,然后使用正则表达式检查..

您可以使用新的 HTML5 表单标签之一,如<input type=number" \\><input type="range" />

Did you consider not writing your own script here?您是否考虑过不在此处编写自己的脚本?

I do use jQuery MaskedInput and it works perfectly for this我确实使用了jQuery MaskedInput ,它非常适合这个

$("#textbox").change(function(){
    //validate the text here
});

I suspect this is because you're returning false for every non-numeric input.我怀疑这是因为您对每个非数字输入都返回 false。

You can either research how to identify things like Ctrl+C, or you can switch to a blacklist approach.您可以研究如何识别诸如 Ctrl+C 之类的东西,也可以切换到黑名单方法。 You really only want to disallow non-numeric printable characters, so you can probably do this with a codepoint range.您真的只想禁止非数字可打印字符,因此您可以使用代码点范围来执行此操作。

If you're using normal Javascript, use the object.onpaste = handler;如果您使用普通的 Javascript,请使用object.onpaste = handler; eg例如

<html>...
    <input id="something" type="text" />
...
  <script>
    var el = document.getElementById('something');
    el.onpaste = function() {
       // do you stuff here
    } ...

Probably better to use onchange使用onchange可能更好

And using a library like jQuery to do it for you is nice.使用像 jQuery 这样的库来为你做这件事很好。

But if you want to learn the innards of javascript... do it yourself!但如果你想学习 JavaScript 的内部结构......自己动手吧! Sometimes it's better to reinvent the wheel when learning.有时在学习时重新发明轮子会更好。

Another approach could be to use setInterval to create your own (pseudo) change listener for form fields.另一种方法是使用setInterval为表单字段创建您自己的(伪)更改侦听器。 See this jsfiddle for an example.有关示例,请参阅此 jsfiddle

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM