allow only numbers in textbox javascript

Hi All, I'm going to explain to allow only numbers in text-box using JavaScript

Today's, I have a requirement to allow only numbers in the contact no., hours, Id etc. textbox using JavaScript, want to allow only numbers or digits and the 
alphabetic and special characters(A to Z a to z.,@#!$%^&*()_+=|\ etc.) are not allowed in the text-box.

These Code samples are working on mostly browsers (IE, Mozilla, Firefox etc.)

In the 1st step, Code Sample for HTML/ASP.Net


<iput id="txt_PhoneNo" type="text" name="txt_PhoneNo" 
onkeypress="return allowNumbersOnly(keyEvent);" >

ASP.Net :

<asp:TextBox id="txt_PhoneNo"
onkeypress="return allowNumbersOnly(keyEvent);" runat="server" />

In the 2st step, Code Sample for JavaScript

<script type="text/javascript" lang="ja">
    //Is used to check the only numbers in the textbox.
    function allowNumbersOnly(keyEvent) {
        var result = (keyEvent.which) ? keyEvent.which : event.keyCode;
        if (result > 31 && (result < 48 || result > 57)) {
            return false;
        } else {
            return true;



Hey! I'm Anil Singh. I author this blog. I'm Active Blogger, Programmer. I love learning new technologies, programming, blogging and participating the forum discussions more...
My Blogs - and
My Books - Interview Questions and Answers Books- Get Your Book in 15+ Digital Stores Worldwide..

You Might Also Like Powered by Blogger.
ASK Questions