How to allow only numeric (0-9) in HTML inputbox using jQuery?

前端 未结 30 2300
一生所求
一生所求 2020-11-21 05:38

I am creating a web page where I have an input text field in which I want to allow only numeric characters like (0,1,2,3,4,5...9) 0-9.

How can I do this using jQuery

30条回答
  •  深忆病人
    2020-11-21 05:56

    You could just use a simple JavaScript regular expression to test for purely numeric characters:

    /^[0-9]+$/.test(input);
    

    This returns true if the input is numeric or false if not.

    or for event keycode, simple use below :

         // Allow: backspace, delete, tab, escape, enter, ctrl+A and .
        if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
             // Allow: Ctrl+A
            (e.keyCode == 65 && e.ctrlKey === true) || 
             // Allow: home, end, left, right
            (e.keyCode >= 35 && e.keyCode <= 39)) {
                 // let it happen, don't do anything
                 return;
        }
    
        var charValue = String.fromCharCode(e.keyCode)
            , valid = /^[0-9]+$/.test(charValue);
    
        if (!valid) {
            e.preventDefault();
        }
    

提交回复
热议问题