tags:

views:

46

answers:

5

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

+4  A: 

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.

cletus
you mean validation using jquery?
Lina
But what happens when the user drags text into the textbox.
rahul
@rahul: paste and drop events are problematic to deal with in pure JS. See http://www.quirksmode.org/dom/events/cutcopypaste.html
cletus
+1 for pure JS...
zaf
+1  A: 

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: http://stackoverflow.com/questions/895659/how-do-i-block-or-restrict-special-characters-from-input-fields-with-jquery

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

zaf
thanks, that sounds logical :)
Lina
+1 for finding it's dup.
jweyrich
This will fail when the user drags text into the textbox.
rahul
Thanks! and now I'm above cletus! I think I'm gonna faint!
zaf
@rahul and what if javascript is disabled? Yes, the server has the final say :)
zaf
right said rahul
nik
+1  A: 

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;

    });
Lina
A: 

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.

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