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

天涯浪子 提交于 2019-11-28 04:49:57

问题


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 similar to this:

$(textField).onKeyPress(function(e) {
    if (e.which < 48 && e.which > 57)
        e.preventDefault();
});

This is fairly strightforward, but turns that (in the latest version of all browsers) Firefox will make this also prevent movement with the arrow keys and delete/backspace keys, whereas the other browsers would not.

Looking around I found that I would need to also check for these keys, and check for different properties exposed in the e event reference.

My final code looks something like this:

$(textField).onKeyPress(function(e) {
    var code = e.which || e.keyCode;
    if (code > 31  // is not a control key
        && (code < 37 || code > 40) // is not an arrow key
        && (code < 48 || code > 57) // is not numeric
        && (code != 46) // is not the delete key
    )
        e.preventDefault();
});

However, this feels to be too much to solve a fairly simple problem as just preventing non-numeric.

What am I doing wrong? Which is the best practice in terms of this kind of validation?


回答1:


We'll respond to both keypresses, and the blur event. When somebody press a key, we check to see if the key entered is a number. If it is, we permit it. Otherwise, we prevent it.

If the field is blurred, we remove any non-numerical values, and all those values that follow. This will prevent the user from pasting in non-numerical strings:

$("#textfield").on("keypress blur", function(e){
    if ( e.type === "keypress" )
        return !!String.fromCharCode(e.which).match(/^\d$/);
    this.value = this.value.replace(/[^\d].+/, "");
});

Demo: http://jsfiddle.net/jonathansampson/S7VhV/5/




回答2:


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

<input type="text" class="hulk" value="" />
​

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,'');
});

​



回答3:


this will allow both int. it also removes text if user copy and paste with mouse.

$(document).ready(function () {
    $('#textfield').bind('keyup blur', function (e) {
        if (e.type == 'keyup') {
            if (parseInt($(this).val()) != $(this).val()) {
                $(this).val($(this).val().slice(0, $(this).val().length - 1));
            }
        } else if (e.type == 'blur') {
            $(this).val('');
        }
    });
});


来源:https://stackoverflow.com/questions/10866444/which-is-the-proper-way-of-filtering-numeric-values-for-a-text-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!