DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Enter Numeric Values In Textbox

  • submit to reddit
        This code restricts the user from accidentally typing characters into a, say, phone number field...

The javascript goes like:
function isNumber(e)
    var code, num, regex;
    code = e.keyCode;
    num = String.fromCharCode(code);
    regex = /\d/;
    return regex.test(num);

The html code goes like:
<input name="txtPhone" type="text" id="txtPhone" onkeypress="javascript:return isNumber(event)" style="width:195px;" />

For firefox/netscape/opera instead of <b>window.event.keyCode</b> use <b>window.event.which</b>