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

前端 未结 30 1777
一生所求
一生所求 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:48

    Here is the function I use:

    // Numeric only control handler
    jQuery.fn.ForceNumericOnly =
    function()
    {
        return this.each(function()
        {
            $(this).keydown(function(e)
            {
                var key = e.charCode || e.keyCode || 0;
                // allow backspace, tab, delete, enter, arrows, numbers and keypad numbers ONLY
                // home, end, period, and numpad decimal
                return (
                    key == 8 || 
                    key == 9 ||
                    key == 13 ||
                    key == 46 ||
                    key == 110 ||
                    key == 190 ||
                    (key >= 35 && key <= 40) ||
                    (key >= 48 && key <= 57) ||
                    (key >= 96 && key <= 105));
            });
        });
    };
    

    You can then attach it to your control by doing:

    $("#yourTextBoxName").ForceNumericOnly();
    

提交回复
热议问题