Don't let a user type the period character in

2019-09-21 03:33发布

So right now the user is able to insert a decimal value in the number field of the HTML5 input type="number". I want to prevent that, so if a user types "5.1" it will insert "51" in the textbox.

Is there any way to do this? Thanks!

标签: html html5
2条回答
Juvenile、少年°
2楼-- · 2019-09-21 04:25

The definite answer is this:

function preventDot(e) {
            var key = e.charCode ? e.charCode : e.keyCode;

            if (key == 46) {
                e.preventDefault();
            }
        }

And bind it on keypress

查看更多
迷人小祖宗
3楼-- · 2019-09-21 04:31

You can use a regular expression to find the characters that make the value a decimal value, and then delete them so that the value internally becomes an integer:

/[\.,]/
查看更多
登录 后发表回答