Monday, 21 January 2013

Forcing html Input element to Numeric Only Input

While developing a shopping cart function for a client, I needed to restrict the user to entering numbers only in an Input field

I came across this handy post;

http://www.itjungles.com/javascript/how-to-use-javascript-to-force-numeric-value-in-textbox

Basically, we need to add the following function to the JavaScript section;

function isNumericKey(evt)
{
    var charCode = (evt.which) ? evt.which : event.keyCode
    if (charCode > 31 && (charCode < 48 || charCode > 57)) 
    {
        return false;
    }
    else
    {
        return true;
    }
}    


We then add the the following to your input element;


onkeypress="return isNumericKey(event)"


Hey Presto! You have a numeric only Input Element!

No comments:

Post a Comment