Allow only numeric value in textbox using Javascript

前端 未结 9 1072
礼貌的吻别
礼貌的吻别 2020-12-19 21:52

I want to allow only numeric values to be entered into the text and if user enters alphabetic character it should warn the user. Any suggestion for optimized and short javas

9条回答
  •  生来不讨喜
    2020-12-19 22:19

    Here is a solution which blocks all non numeric input from being entered into the text-field.

    html

    
    

    javascript

    var input = document.getElementById('numbersOnly');
    input.onkeydown = function(e) {
        var k = e.which;
        /* numeric inputs can come from the keypad or the numeric row at the top */
        if ( (k < 48 || k > 57) && (k < 96 || k > 105)) {
            e.preventDefault();
            return false;
        }
    };​
    

提交回复
热议问题