HTML text input allow only numeric input

前端 未结 30 4061
孤街浪徒
孤街浪徒 2020-11-21 04:58

Is there a quick way to set an HTML text input () to only allow numeric keystrokes (plus \'.\')?

30条回答
  •  生来不讨喜
    2020-11-21 05:26

    Use this DOM:

    
    

    And this script:

    validate = function(evt)
    {
        if ([8, 46, 37, 39, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 35, 36].indexOf(evt.keyCode || evt.which) == -1)
        {
            evt.returnValue = false;
            if(evt.preventDefault){evt.preventDefault();}
        }
    }
    

    ...OR this script, without indexOf, using two for's...

    validate = function(evt)
    {
        var CharValidate = new Array("08", "046", "039", "948", "235");
        var number_pressed = false;
        for (i = 0; i < 5; i++)
        {
            for (Ncount = 0; Ncount < parseInt(CharValidate[i].substring(0, 1)) + 1; Ncount++)
            {
                if ((evt.keyCode || evt.which) == parseInt(CharValidate[i].substring(1, CharValidate[i].lenght)) + Ncount)
                {
                    number_pressed = true;
                }
            }
        }
        if (number_pressed == false)
        {
            evt.returnValue = false;
            if(evt.preventDefault){evt.preventDefault();}
        }
    }
    

    I used the onkeydown attribute instead of onkeypress, because the onkeydown attribute is checked before onkeypress attribute. The problem would be in the Google Chrome browser.

    With the attribute "onkeypress", TAB would be uncontrollable with "preventDefault" on google chrome, however, with the attribute "onkeydown", TAB becomes controllable!

    ASCII Code for TAB => 9

    The first script have less code than the second, however, the array of ASCII characters must have all the keys.

    The second script is much bigger than the first, but the array does not need all keys. The first digit in each position of the array is the number of times each position will be read. For each reading, will be incremented 1 to the next one. For example:




    NCount = 0

    48 + NCount = 48

    NCount + +

    48 + NCount = 49

    NCount + +

    ...

    48 + NCount = 57




    In the case of numerical keys are only 10 (0 - 9), but if they were 1 million it would not make sense to create an array with all these keys.

    ASCII codes:

    • 8 ==> (Backspace);
    • 46 => (Delete);
    • 37 => (left arrow);
    • 39 => (right arrow);
    • 48 - 57 => (numbers);
    • 36 => (home);
    • 35 => (end);

提交回复
热议问题