How to block +,-,e in input type Number?

后端 未结 13 1848
我在风中等你
我在风中等你 2020-12-29 20:52

When I\'m giving input type number the letter e and special charecters are also displaying in input field. I want to display only digits. How to block them?

13条回答
  •  遥遥无期
    2020-12-29 21:24

    Following form from the answers above, most of the examples above cover it, i just noticed that when inputting "E" this is still allowable so i think its best to add this into the array. I am using Jquery 3.3.1 in this example.

    Also that way whatever you enter into the array will be prevented from being keyed in into the input box

    Note - take the 'elementid' as the id of the element you want to apply this to similarly if you want to apply this to all inputs that are type number in JQuery --> $("input[type='number']")

    var invalidChars = ["-", "e", "+", "E"];
    
    $("input[type='number']").on("keydown", function(e){ 
        if(invalidChars.includes(e.key)){
             e.preventDefault();
        }
    }):
    

    This sample above should work on all inputs with a type of number and prevent the characters "-", "e", "+" and "E" from being keyed into the input.

    UPDATE

    Just also notices that you are able to enter '.' as they represent decimal points which is valid for numbers. I was using this validating a telephone number and obviously (for UK) there is no '.' so that may also be another character to add to your array.

提交回复
热议问题