Input max length checking

时间:2016-04-18 10:44:13

标签: javascript html css

I have a problem with "checkNumbers()". I'm trying to check if my input is not bigger than 10 numbers; "isAllowedSymbol()" is working great, but another don't. What is my problem?

 function isAllowedSymbol(input)
        { 
            var value = input.value; 
            var rep = /[a-zA-Z]/;
            var rep2 = /[а-яА-Я]/;

        if (rep.test(value))
        { 
        value = value.replace(rep, ''); 
        input.value = value; 
                if (rep2.test(value))
                { 
                value = value.replace(rep2, ''); 
                input.value = value; 
                }
        } 
    }
    var element = document.querySelector("input[name=answer]");


    function checkNumbers(element) {
      if (element != null && element.value.length > 10) {
        element = element.replace(element, '');
      }
    }

<input type="text" maxlength="10" name="answer" onkeyup="isAllowedSymbol(this);checkNumbers(this);" placeholder="Enter data" > <br>

2 个答案:

答案 0 :(得分:0)

您已使用maxlength = 10作为输入,因此您无法为其添加任何新字符,从而导致element.value.length > 10永远不会发生的情况。

使用此:

function isAllowedSymbol(input)
        { 
            var value = input.value; 
            var rep = /[a-zA-Z]/;
            var rep2 = /[а-яА-Я]/;

        if (rep.test(value))
        { 
        value = value.replace(rep, ''); 
        input.value = value; 
                if (rep2.test(value))
                { 
                value = value.replace(rep2, ''); 
                input.value = value; 
                }
        } 
    }
    var element = document.querySelector("input[name=answer]");


    function checkNumbers(element) {
      if (element != null && element.value.length > 10) {
        element.value = ''
      }
    }
<input type="text" maxlength="15" name="answer" onkeyup="isAllowedSymbol(this);checkNumbers(this);" placeholder="Enter data" > <br>

答案 1 :(得分:0)

首先你想做什么? 如果你想输入超过10的输入框然后输入框将被清除,那么首先在输入框的maxlength属性中编辑

<input type="text" maxlength="15" name="answer" onkeyup="isAllowedSymbol(this);checkNumbers(this); " placeholder="Enter data">
相关问题