Silambarasan
Silambarasan

Reputation: 309

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?

Upvotes: 0

Views: 5166

Answers (7)

KooiInc
KooiInc

Reputation: 122916

Another approach could be to use setInterval to create your own (pseudo) change listener for form fields. See this jsfiddle for an example.

Upvotes: 0

Vincent McNabb
Vincent McNabb

Reputation: 34689

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.

Upvotes: 0

Tom
Tom

Reputation: 9127

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.

Upvotes: 0

Ritik Khatwani
Ritik Khatwani

Reputation: 549

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

Upvotes: 0

user278064
user278064

Reputation: 10180

You can use one of the new HTML5 form tags, as <input type=number" \> or <input type="range" />.

Upvotes: 2

Tigraine
Tigraine

Reputation: 23648

Did you consider not writing your own script here?

I do use jQuery MaskedInput and it works perfectly for this

Upvotes: 1

Dmitry Aleksandrov
Dmitry Aleksandrov

Reputation: 710

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

Upvotes: 2

Related Questions