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

后端 未结 3 1904
时光取名叫无心
时光取名叫无心 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:14

    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/

提交回复
热议问题