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

前端 未结 30 1760
一生所求
一生所求 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-21 06:01

    function suppressNonNumericInput(event){

        if( !(event.keyCode == 8                                // backspace
            || event.keyCode == 46                              // delete
            || (event.keyCode >= 35 && event.keyCode <= 40)     // arrow keys/home/end
            || (event.keyCode >= 48 && event.keyCode <= 57)     // numbers on keyboard
            || (event.keyCode >= 96 && event.keyCode <= 105))   // number on keypad
            ) {
                event.preventDefault();     // Prevent character input
        }
    }
    

提交回复
热议问题