Sunday, December 19, 2010

Javascript Tips : Javascript numeric only for input type text (TextBox)

How to create javascript numeric only input text (TextBox)?
I have made some script to solve this problem:
Here's a full example below:
================================================================
<html>
   <head>
   <title>
   Test Numeric Only
   </title>
   <script language=Javascript>

      function numericOnly(evt)
      {
         var key = (evt.which) ? evt.which : event.keyCode
         if (key > 31 && (key < 48 || key > 57)){
            document.getElementById("LabelValid").style.display = "block";
            return false;
        }
         document.getElementById("LabelValid").style.display = "none";
         return true;
      }
   </script>
   </head>
   <body>
      Numeric Only : <input id="TextBoxChar" onkeypress="return numericOnly(event)" type="text" name="TextBoxChar">
      <label id="LabelValid" style="display:none">(*)</label>
   </body>
</html>
================================================================
The "numericOnly" function is called by onkeypress event attribute of the input text (TextBox). The "numericOnly" function will return false if the user type a non-numeric character in the textbox. and I have added a validation label that will show "(*)" if the user type a non-numeric character, and will disappear if the user type a numeric value.

If you find my post helpful, please leave a comment...

Thank you....

No comments:

Post a Comment

Finally, C# 9 record, the equivalent of Scala's case class

While C# is a wonderful programming language, there is something that I would like to see to make our life programmer easier. If you are fam...