如何设置文本框只接受特定范围内的数字

时间:2019-05-02 13:53:40

标签: javascript html

范围可以是5到10 到目前为止,这是我所做的,但仍然没有做到我想要的

<script>
function checkpattern(elem)
{
    var textbox = document.getElementById("textbox");

    if(textbox.value.length<=10 && textbox.value.length>=5)
    {
        alert("5 to 10");
    }
    else
    {
        if(!elem.value.match('^'+elem.getAttribute('pattern')+'$'))
        {
            alert('Accepts digits only');
        }
    }
}
</script>

<input type = "text" name = "amt" maxlength = "10" pattern = [0-9] onchange = checkpattern(this) placeholder="Enter Amount" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Enter Amount '" required="">

2 个答案:

答案 0 :(得分:1)

如果您使用minlength,除非它的字符数超过5个,否则它将不允许您提交

<input type = "text" name = "amt" minlength="5" maxlength = "10" pattern = [0-9] onchange = checkpattern(this) placeholder="Enter Amount" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Enter Amount '" required="">

如果要将其设置为数量(数字),则可以使用minmax

<input type = "number" name = "amt" min="5" max = "10" pattern = [0-9] onchange = checkpattern(this) placeholder="Enter Amount" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Enter Amount '" required="">

答案 1 :(得分:0)

您的代码中有很多问题,如果其他地方不对,并且您也没有正确传递输入值

 <script>
function checkpattern(elem)
        {

            if(elem<=10 && elem>=5)
            {
            alert("5 to 10");
            }
                if(!elem.match(/^\d+$/))
            {
                alert('Accepts digits only');
            }

        }
</script>
<input type = "text" name = "amt" maxlength = "10" pattern = [0-9] onchange = checkpattern(this.value) placeholder="Enter Amount" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Enter Amount '" required="">