Others



Allow only numbers in input using JavaScript


The following example shows how to enter only numbers in input using JavaScript.We can filter the input values with the following 'onlyNumbers' and 'numberValidation' user defined JavaScript functions.

Example
<!DOCTYPE html>
<html>
 <body>
  <h1>Allow only Numeric Input</h1>
  <input type='text' onkeypress="return onlyNumbers(event)" onkeyup="return numberValidation(event)">
 <script>
  function onlyNumbers(e)
  {
    var c=e.which?e.which:e.keyCode; 
    if(c<48||c>57)
    {
      return false;
    }
  }
  function numberValidation(e){
      e.target.value = e.target.value.replace(/[^\d]/g,'');
      return false;
  }
 </script>
</body>
</html>
Try it Yourself

Live Demo