简体   繁体   中英

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). 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.

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

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

I suspect this is because you're returning false for every non-numeric input.

You can either research how to identify things like Ctrl+C, or you can switch to a blacklist approach. 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; 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

And using a library like jQuery to do it for you is nice.

But if you want to learn the innards of javascript... do it yourself! 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. See this jsfiddle for an example.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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