HTML text input allow only numeric input

前端 未结 30 3503
孤街浪徒
孤街浪徒 2020-11-21 04:58

Is there a quick way to set an HTML text input () to only allow numeric keystrokes (plus \'.\')?

30条回答
  •  悲哀的现实
    2020-11-21 05:31

    The best way (allow ALL type of numbers - real negative, real positive, iinteger negative, integer positive) is:

    $(input).keypress(function (evt){
        var theEvent = evt || window.event;
        var key = theEvent.keyCode || theEvent.which;
        key = String.fromCharCode( key );
        var regex = /[-\d\.]/; // dowolna liczba (+- ,.) :)
        var objRegex = /^-?\d*[\.]?\d*$/;
        var val = $(evt.target).val();
        if(!regex.test(key) || !objRegex.test(val+key) || 
                !theEvent.keyCode == 46 || !theEvent.keyCode == 8) {
            theEvent.returnValue = false;
            if(theEvent.preventDefault) theEvent.preventDefault();
        };
    }); 
    

提交回复
热议问题