HTML input tag that accepts only numeric values using JavaScript

I need to restrict certain number of input field to takes only numbers values. Basically my form is not a submit form so that i can not put the simple validation on the form submission. I want the user to be unable to enter the any other characters than numeric values.
For it i am using the .keydown() jQuery event that will trigger each time when user keydown in the input tag. To create the generic functionality i am using the .keydown() event on the class selector.

Demo

Enter Only numeric values:

Number of the total Years:

Number of the Total Days:

I have a form that contains certain number of input tag, i put the class name ‘onlynumeric’ on these input tags.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
      <script type="text/javascript">
          $(function() {
              $('.onlynumeric').keydown(function(e) {
                  RestrictNonNumeric(e);
              });
              function RestrictNonNumeric(e) {
                  if (e.shiftKey || e.ctrlKey || e.altKey) { // if shift, ctrl or alt keys held down
                      e.preventDefault();         // Prevent character input
                      $(e.target).css({ 'border-color': '#FF0000' });
                      return;
                  }
                  else {
                      var n = e.keyCode;
                      if (!((n == 8)              // backspace
                || (n == 9)
                || (n == 46)                // delete
                || (n >= 35 && n <= 40)     // arrow keys/home/end
                || (n >= 48 && n <= 57)     // numbers on keyboard
                || (n >= 96 && n <= 105))   // number on keypad
                ) {
                          e.preventDefault(); // Prevent character input
                          $(e.target).css({ 'border-color': '#FF0000' });
                          return;
                      };
                  };
                  $(e.target).css({ 'border-color': '#eee' });
              }
 
          });
      </script>
 
</head>
<body>
    <form id="form1" runat="server">
    <div>
       Number of the total Years:<input id="txtweight" type="text" class="onlynumeric"/></br>
       Number of the Total Days:<input id="txtheight" type="text" class="onlynumeric" />
    </div>
    </form>
</body>
</html>

Author: Hirendra Sisodiya

Programmer at PSPL. Can be found on Google Plus.