Search code examples
javascriptkeycode

JavaScript keycode allow number and plus symbol only


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

Solution

  • 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.