Numeric Validation in Java Script

Introduction 

 
In your HTML page add the control you want to validate but for this sample, I used textbox to demonstrate this code, in my textbox control I used onkeyup event to validate whether recently entered character is numeric or not. so you can call this JavaScript code as your requirement in your project.
 
Test.html
  1. <input type="text" id="txt" name="txt" onkeyup="txtValidate(this.id)"/>  
JavaScript Code
  1. function txtValidate(txtid)   
  2. {  
  3.      var ok = 0;  
  4.      var a = document.getElementById(txtid).value;  
  5.   
  6.      for (var i = 0; i <= a.length - 1; i++)   
  7.      {  
  8.           var j = a.charCodeAt(i);  
  9.           for (var k = 48; k <= 57; k++)   
  10.           {  
  11.                ok = 0;  
  12.   
  13.                if (k == j)  
  14.                {  
  15.                     ok = 1;  
  16.                     break;  
  17.                }  
  18.           }  
  19.   
  20.      }  
  21.   
  22.      if (ok == 0)   
  23.      {  
  24.           alert("Only Numeric Values Allowed");  
  25.           document.getElementById(txtid).value = "";  
  26.           for (var i = 0; i < a.length - 1; i++)   
  27.           {  
  28.                var j = a.charCodeAt(i);  
  29.                for (var k = 48; k <= 57; k++)   
  30.                {  
  31.                     ok = 0;  
  32.   
  33.                     if (k == j)  
  34.                     {  
  35.                          document.getElementById(txtid).value += a.charAt(i);  
  36.                     }  
  37.                }  
  38.   
  39.           }  
  40.      }  
  41. }  
I hope this code helps you. Thank you.