Which is the proper way of filtering numeric values for a text field?

后端 未结 3 1902
时光取名叫无心
时光取名叫无心 2020-12-19 17:44

I\'m working on a textfield working with the kind of validation that wouldn\'t let you enter other than numeric values. As so, my initial code looked quite simple and simila

3条回答
  •  [愿得一人]
    2020-12-19 18:21

    Working demo http://jsfiddle.net/Pb2eR/23/ Updated Copy/Paste demo: http://jsfiddle.net/Pb2eR/47/ (In this demo wit you copy paste string with characters it won't allow else it will allow number to be copy pasted: tested in safari)

    Demo for arrow key to work http://jsfiddle.net/gpAUf/

    This will help you.

    Note: in this version even if you copy paste it will set it to empty input box, tested in safari lion osx :)

    Good Link: [1] How to allow only numeric (0-9) in HTML inputbox using jQuery?

    code

    $(".hulk").keyup(function(){    
        this.value = this.value.replace(/[^0-9\.]/g,'');    
    });
    ​
    

    html

    Update for copy paste stuff

    $(".hulk").keyup(function(){
    
        this.value = this.value.replace(/[^0-9\.]/g,'');
    
    });
    
    $(".hulk").bind('input propertychange', function() {
    
         this.value = this.value.replace(/[^0-9\.]/g,'');
    });​
    

    code from another demo

    $(".hulk").bind('input propertychange', function(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
        }
         this.value = this.value.replace(/[^0-9\.]/g,'');
    });
    
    ​
    

提交回复
热议问题