JavaScript keycode allow number and plus symbol only

cyberfly picture cyberfly · Apr 4, 2011 · Viewed 38.5k times · Source

I have this JavaScript function that is used to force user only type number in the textbox. Right now and I want to modify this function so it will allow the user to enter plus (+) symbol. How to achieve this?

//To only enable digit in the user input

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

Answer

dominicbri7 picture dominicbri7 · Apr 4, 2011

Since the '+' symbol's decimal ASCII code is 43, you can add it to your condition.

for example :

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

This way, the Plus symbol is allowed.