我正在创建一个网页,其中我有一个输入文本字段,我想只允许数字字符,如(0,1,2,3,4,5…9)0-9。

我如何使用jQuery做到这一点?


当前回答

你可以使用这个JavaScript函数:

function maskInput(e) {
    //check if we have "e" or "window.event" and use them as "event"
        //Firefox doesn't have window.event 
    var event = e || window.event 

    var key_code = event.keyCode;
    var oElement = e ? e.target : window.event.srcElement;
    if (!event.shiftKey && !event.ctrlKey && !event.altKey) {
        if ((key_code > 47 && key_code < 58) ||
            (key_code > 95 && key_code < 106)) {

            if (key_code > 95)
                 key_code -= (95-47);
            oElement.value = oElement.value;
        } else if(key_code == 8) {
            oElement.value = oElement.value;
        } else if(key_code != 9) {
            event.returnValue = false;
        }
    }
}

你可以像这样把它绑定到你的文本框:

$(document).ready(function() {
    $('#myTextbox').keydown(maskInput);
});

我在生产中使用了上面的方法,它工作得很好,而且是跨浏览器的。此外,它不依赖于jQuery,所以你可以用内联JavaScript将它绑定到你的文本框:

<input type="text" name="aNumberField" onkeydown="javascript:maskInput()"/>

其他回答

我在我们的内部common js文件中使用了这个。我只是将类添加到需要这种行为的任何输入中。

$(".numericOnly").keypress(function (e) {
    if (String.fromCharCode(e.keyCode).match(/[^0-9]/g)) return false;
});
/**
Makes the textbox to accept only numeric input
*/

(function($) {
    $.fn.allowOnlyNumeric = function() {

        /**
        The interval code is commented as every 250 ms onchange of the textbox gets fired.
        */

        //  var createDelegate = function(context, method) {
        //      return function() { method.apply(context, arguments); };
        //  };

        /**
        Checks whether the key is only numeric.
        */
        var isValid = function(key) {
            var validChars = "0123456789";
            var validChar = validChars.indexOf(key) != -1;
            return validChar;
        };

        /**
        Fires the key down event to prevent the control and alt keys
        */
        var keydown = function(evt) {
            if (evt.ctrlKey || evt.altKey) {
                evt.preventDefault();
            }
        };

        /**
        Fires the key press of the text box   
        */
        var keypress = function(evt) {
            var scanCode;
            //scanCode = evt.which;
            if (evt.charCode) { //For ff
                scanCode = evt.charCode;
            }
            else { //For ie
                scanCode = evt.keyCode;
            }

            if (scanCode && scanCode >= 0x20 /* space */) {
                var c = String.fromCharCode(scanCode);
                if (!isValid(c)) {
                    evt.preventDefault();
                }
            }
        };

        /**
        Fires the lost focus event of the textbox   
        */
        var onchange = function() {
            var result = [];
            var enteredText = $(this).val();
            for (var i = 0; i < enteredText.length; i++) {
                var ch = enteredText.substring(i, i + 1);
                if (isValid(ch)) {
                    result.push(ch);
                }
            }
            var resultString = result.join('');
            if (enteredText != resultString) {
                $(this).val(resultString);
            }

        };

        //var _filterInterval = 250;
        //var _intervalID = null;

        //var _intervalHandler = null;

        /**
        Dispose of the textbox to unbind the events.
        */
        this.dispose = function() {
            $(this).die('change', onchange);
            $(this).die('keypress', keypress);
            $(this).die('keydown', keydown);
            //window.clearInterval(_intervalHandler);
        };

        $(this).live('change', onchange);
        $(this).live('keypress', keypress);
        $(this).live('keydown', keydown);
        //_intervalHandler = createDelegate(this, onchange);
        //_intervalID = window.setInterval(_intervalHandler, _filterInterval);
    }
})(jQuery);

上面的$ plugin是从AjaxControlToolkit过滤器文本框extender.js编写的。

然而,有一个行为并没有从AjaxControlToolkit中借用,那就是当用户复制和粘贴任何非数字值时,onchange事件就会触发,文本框就会吞噬这些值。我检查了代码,发现这个onchange在每250ms之后被调用,这是一个性能打击,因此注释了这部分。

如果你必须解决变音符和特殊字符,尝试使用这个:

$(this).on( 'keypress', function( e )
{
    // Ensure that it is a number and stop the keypress
    if (e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) {
        e.preventDefault();
    }
});  

这个jQuery代码可以过滤掉按住Shift, Ctrl或Alt时键入的字符。

$('#AmountText').keydown(function (e) {
    if (e.shiftKey || e.ctrlKey || e.altKey) { // if shift, ctrl or alt keys held down
        e.preventDefault();         // Prevent character input
    } else {
        var n = e.keyCode;
        if (!((n == 8)              // backspace
        || (n == 46)                // delete
        || (n >= 35 && n <= 40)     // arrow keys/home/end
        || (n >= 48 && n <= 57)     // numbers on keyboard
        || (n >= 96 && n <= 105))   // number on keypad
        ) {
            e.preventDefault();     // Prevent character input
        }
    }
});

这似乎牢不可破。

// Prevent NULL input and replace text.
$(document).on('change', 'input[type="number"]', function (event) {
    this.value = this.value.replace(/[^0-9\.]+/g, '');
    if (this.value < 1) this.value = 0;
});

// Block non-numeric chars.
$(document).on('keypress', 'input[type="number"]', function (event) {
    return (((event.which > 47) && (event.which < 58)) || (event.which == 13));
});