Documentation and Books

Recent site activity

Web Development‎ > ‎JavaScript‎ > ‎

How to force a textfield to only allow digits?

The following function removes all the non-digit numbers from a text field (so it also works with pasting a piece of text):

  function numbersOnly(field) {
field.value = field.value.replace(/[^0-9]/g, "");
}

Use this function in combination with the following HTML snippet example:

 <input type="text" size="8" onkeyup="numbersOnly(this);"/>