目的:

强制进行校验文本字段的键盘输入,用户只能输入数值

代码:

有几个在线资源描述这个 (e.g. http://stackoverflow.com/questions/995183/how-to-allow-only-numeric-0-9-in-html-inputbox-using-jqueryhttp://snipt.net/GerryEng/jquery-making-textfield-only-accept-numeric-values, etc.).

例如,如果您的文本字段ID是“numeric”,则可以使用此示例脚本:

<script>
$(document).ready(function() {
    $("#numeric").keydown(function(event) {
        // Allow only backspace and delete
        if ( event.keyCode == 46 || event.keyCode == 8 ) {
            // let it happen, don't do anything
        }
        else {
            // Ensure that it is a number and stop the keypress
            if (event.keyCode < 48 || event.keyCode > 57 ) {
                event.preventDefault();
            }
        }
    });
});
</script>
  • No labels