Friday, April 9, 2010

Javscript code for not allowing charecters in text box

Some times we may have the requirement to not allow the characters into text input such as rupees or telephone no. In this case calling the below function onkeypress event is the better practice. This method doesn't allow the user to enter the characters except numerals and decimal value.

var isNS4 = (navigator.appName=="Netscape")?1:0;
function checkCharacter(event){
        if(!isNS4){
            if(event.keyCode == 8 || event.keyCode == 0 ) return true;
            if(event.keyCode < 46 || event.keyCode > 57 ) {
                event.returnValue = false;               
            }
        }
        else{
            if(event.which == 8 || event.which == 0 ) return true;
            if(event.which < 46 || event.which > 57 ) {
                return false;               
            }
        }
    }