How to allow only numeric (0-9) in HTML inputbox using jQuery?

前端 未结 30 1774
一生所求
一生所求 2020-11-21 05:38

I am creating a web page where I have an input text field in which I want to allow only numeric characters like (0,1,2,3,4,5...9) 0-9.

How can I do this using jQuery

30条回答
  •  余生分开走
    2020-11-21 05:52

    Here is an answer that uses jQuery UI Widget factory. You can customize what characters are allowed easily.

    $('input').numberOnly({
        valid: "0123456789+-.$,"
    });
    

    That would allow numbers, number signs and dollar amounts.

    $.widget('themex.numberOnly', {
        options: {
            valid : "0123456789",
            allow : [46,8,9,27,13,35,39],
            ctrl : [65],
            alt : [],
            extra : []
        },
        _create: function() {
            var self = this;
    
            self.element.keypress(function(event){
                if(self._codeInArray(event,self.options.allow) || self._codeInArray(event,self.options.extra))
                {
                    return;
                }
                if(event.ctrlKey && self._codeInArray(event,self.options.ctrl))
                {
                    return;
                }
                if(event.altKey && self._codeInArray(event,self.options.alt))
                {
                    return;
                }
                if(!event.shiftKey && !event.altKey && !event.ctrlKey)
                {
                    if(self.options.valid.indexOf(String.fromCharCode(event.keyCode)) != -1)
                    {
                        return;
                    }
                }
                event.preventDefault(); 
            });
        },
    
        _codeInArray : function(event,codes) {
            for(code in codes)
            {
                if(event.keyCode == codes[code])
                {
                    return true;
                }
            }
            return false;
        }
    });
    

提交回复
热议问题