Allowing just Numeric Text on Input Text field

后端 未结 3 1870
渐次进展
渐次进展 2021-02-09 00:11

I was using Jquery Numeric plugin but I found that is not working on FireFox 3.6 on Osx (does not allow pasting).

I\'m searching a Jquery plugin or Javascript snippet

相关标签:
3条回答
  • 2021-02-09 00:16

    Thanks to dev-null-dweller i have resolved with this script:

    jQuery('#input').bind('keyup blur',function(){ 
       jQuery(this).val( jQuery(this).val().replace(/[^0-9]/g,'') ); }
    );
    
    0 讨论(0)
  • 2021-02-09 00:21

    Thanks systempuntoout.. I've fixed this with following script

    $('#input').keyup( function() {
      var $this = $(this);
      $this.val($this.val().replace(/[^\d.]/g, ''));     
    });
    
    0 讨论(0)
  • 2021-02-09 00:36

    DEMO: http://so.devilmaycode.it/allowing-just-numeric-text-on-input-text-field/

    jQuery.fn.onlyDigits = function() {
        var k;
        // little trick just in case you want use this:
        $('<span></span>').insertAfter(this);
        var $dText = $(this).next('span').hide();
        // Really cross-browser key event handler
        function Key(e) {
            if (!e.which && ((e.charCode ||
            e.charCode === 0) ? e.charCode: e.keyCode)) {
            e.which = e.charCode || e.keyCode;
            } return e.which; }
        return $(this).each(function() {
            $(this).keydown(function(e) {
                k = Key(e);
                return (
                // Allow CTRL+V , backspace, tab, delete, arrows,
                // numbers and keypad numbers ONLY
                ( k == 86 && e.ctrlKey ) || (k == 86 && e.metaKey) || k == 8 || k == 9 || k == 46 || (k >= 37 && k <= 40 && k !== 32 ) || (k >= 48 && k <= 57) || (k >= 96 && k <= 105));
            }).keyup(function(e) {
                var value = this.value.replace(/\s+/,'-');
                // Check if pasted content is Number
                if (isNaN(value)) {
                    // re-add stored digits if CTRL+V have non digits chars
                    $(this).val($dText.text());
                } else { // store digits only of easy access
                    $dText.empty().append(value);
                }
            });
        });
    };
    

    USAGE:

    $("#onlydigits").onlyDigits();
    

    NOTE:

    thanks to Insider for pointing out the past (cmd+v) for MAC


    key event handler REFERENCES:

    • http://unixpapa.com/js/key.html
    • http://www.hallvord.com/opera/keyevents.htm
    • http://dev.opera.com/articles/view/keyboard-accessible-web-applications-3/
    • http://qooxdoo.org/documentation/0.7/keyboard_events
    • http://msdn.microsoft.com/en-us/library/ms533927(VS.85).aspx
    • http://www.quirksmode.org/js/keys.html
    • http://www.w3.org/2002/09/tests/keys-cancel2.html
    0 讨论(0)
提交回复
热议问题