Wednesday, 5 February 2014

HTML text box to allow numbers only

We generally encounter the need of functionality where text boxes need to be filled with numbers only(may be for security/validation). We have a easy JavaScript solution for this -

<!DOCTYPE html>
<html>
<script>
 function CheckNumeric(event)
{
    var key = window.event ? event.keyCode : event.which;
    //Check for backspace, delete, left arrow and right arrow keys
    if (event.keyCode == 8  || event.keyCode == 46 || event.keyCode == 37 || event.keyCode == 39)
    {
        return true;
    }
    //All other keys excluding numeric keys
    else if ( key < 48 || key > 57 )
    {
        return false;
    }
    else return true; //Numeric keys from 0 to 9
};
</script>


<body>
<input type="text" id="txtSample" name="txtSample" onkeypress="return CheckNumeric(event)" />
</body>


</html>


Alternatively, there is one more method to use input types as numbers only. Here you can also set restrictions on what numbers are accepted. Its HTML5 way -
Cons: It is not supported through all browsers and their versions.

<!DOCTYPE html>
<html>
<body>

<form action="demo_form.asp">
  Quantity (between 1 and 5): <input type="number" name="quantity" min="1" max="5">
  <input type="submit">
</form>

<p><b>Note:</b> type="number" is not supported in Internet Explorer 9 and earlier versions.</p>

</body>
</html>