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

Game Development: Text 101 - Text Based Game With Finite State Machine

This time, I've created a really simple text based game that allow the player to progress state to another state by choosing some option...