bombo
bombo

Reputation: 1871

limit the choices of acceptable inputs using javascript

Is it possible to prevent user from writing letters to a textbox (i.e. force user to enter only numbers in textbox) using javascript?

Upvotes: 0

Views: 281

Answers (5)

zaf
zaf

Reputation: 23244

If you don't fancy writing it from scratch you can use the following jQuery plugin: http://www.itgroup.com.ph/alphanumeric/ and then writing:

$('#id').numeric();

And its been asked before here: how do i block or restrict special characters from input fields with jquery?

ADDITIONAL: And make sure you validate on the server regardless!

Upvotes: 1

cletus
cletus

Reputation: 625087

Sure, you put an event handler on keydown events and cancel those for non-digits when the relevant text box has the focus. See element.onkeydown event.

You can of course do this in vanilla Javascript but like many things, it's easier with a library (like jQuery).

For example, assuming:

<input id="one" type="text">
<input id="two" type="text">

try:

document.getElementById("one").onkeydown = numbers_only;

function numbers_only(evt) {
  return evt.keyCode >= 48 && evt.keyCode <= 57;
}

The first should only allow digits.

Upvotes: 5

jweyrich
jweyrich

Reputation: 32240

$('#input-id').bind('keypress', function(e) { 
    return !((e.which < 48 || e.which > 57) && e.which != 8 && e.which != 0);
})

Upvotes: 0

rahul
rahul

Reputation: 187050

If you want to catch this on a submit event then you can use regex to do that in the submit event hanlder.

But if you want to do this when the user interaction with the text box is going on then you will have to manipulate keydown and focus events. By wiring only keypress or keydown events will not prevent the user from entering other characters. He can also drag text into the text box. So focus event will prevent that from happening.

Upvotes: 0

bombo
bombo

Reputation: 1871

the exact code that i was looking for is:

 $('#id').bind('keypress', function (e) {

        return (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) ? false : true;

    });

Upvotes: 1

Related Questions