输入类型文本最多2位数

时间:2018-06-05 10:21:19

标签: html validation input html-input

我知道这可以从type="number"开始,但是我不能使用这个,因为我还有pattern一些与它不兼容的正则表达式。

有没有办法限制type="text"的输入? (在我的特殊情况下,限制小数点后最多2位数。)

1 个答案:

答案 0 :(得分:0)

如果您想在'。'之后限制2个字符上的字符数,您可以检查总数是否真的是数字

并在'之后停止2个字符后的脚本。'

(我使用e.wich == 8阻止删除键)

<!DOCTYPE html>
<html>
<head>
<script>
function myFunction(e) {
    var x = document.getElementById("numb").value;
    var carac = (e.which == 8) ? '' : String.fromCharCode(e.which);
    var nbr = x + carac;
        if ( isNaN(nbr) ) {
          e.preventDefault();
          document.getElementById("numb").value = '';
          alert ( 'Please write a Number!' );
        }

    if(! Number.isInteger(nbr*100)) {
        e.preventDefault();
        //document.getElementById("numb").value = '';
    }
}
</script>
</head>
<body>

<p>A function is triggered when the user is pressing a key in the input field.</p>

<input id="numb" type="text" onkeypress="myFunction(event)">

</body>
</html>