javascript (jquery) numeric input: keyCode for '3' and '#' are the same

前端 未结 4 2093
面向向阳花
面向向阳花 2021-01-17 23:33

I need to set up an so that it will accept only numeric chars, backspace, delete, enter, tabs and arrows.

There\'s a lot o

4条回答
  •  执念已碎
    2021-01-18 00:04

    Why not do something like this? It uses a combination of the keyup() event and isNaN(). It'll work whether the user types with the keyboard or pastes a number.

    The way it works is, as soon as the text changes, it will check if the value is a number. If not, it will trim the input until it is a number. So, if you enter 25s or 25ss, you will be left with 25.

    This will work with ctrl+v paste as well. It won't work with right-click paste and for that reason, I have disabled right-clicking only on the textbox.

    Live Demo

    The Jquery

    $(document).ready(function(){
        $('#number').keyup(function(){    
            var input = this.value;
            while (isNaN(input))
            {
                input = input.substring(0,input.length-1);
                $('#number').val(input);             
            }
        });
        $('#number').bind("contextmenu",function(e){
            return false;
        });
    });
    

提交回复
热议问题