Friday, 20 December 2013

How to allow HTML Textbox to accept Numbers only using Javascript?

How to allow HTML Textbox to accept Numbers only using Javascript?

While web development, you often encounter the need of functionality where your textboxes should be filled with numbers only.

For example, you want your users to fill the quantity of anything, ID (if it is composed on integers only), price of anything (excluding decimal) etc. In short, you want only numbers plus some keys like backspace, delete. left and right arrow to be typed in the textbox. You can use javascript to restrict your users to fill only numbers in the textbox. It is very simple. On the KeyPress event of any HTML text, just call a simple javascript function which checks the keycodes for the numbers and on the basis of keycodes, it returns true or false. Here is how?

HTML Text

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

Javascript 

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
};

No comments:

Post a Comment