最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

string - Enter only number in text box by javascript onkeypress problem - Stack Overflow

programmeradmin1浏览0评论

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 e 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?

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 e 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?

Share Improve this question edited May 15, 2020 at 17:33 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked Jul 28, 2011 at 8:43 SilambarasanSilambarasan 3092 gold badges4 silver badges15 bronze badges 1
  • @op , you should do a validation on the server anyway . Regarding your current problem , try using the onchange event . – amal Commented Jul 28, 2011 at 8:48
Add a ment  | 

7 Answers 7

Reset to default 2

May be you can try use onchange event and then check with regex..

You can use one of the new HTML5 form tags, as <input type=number" \> or <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; e.g.

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

发布评论

评论列表(0)

  1. 暂无评论