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

范围可能是例如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="">


蓝山帝景
浏览 207回答 2
2回答

繁星淼淼

如果您使用minlength它,除非它的字符数超过5个,否则不会让您提交它<input&nbsp;type&nbsp;=&nbsp;"text"&nbsp;name&nbsp;=&nbsp;"amt"&nbsp;minlength="5"&nbsp;maxlength&nbsp;=&nbsp;"10"&nbsp;pattern&nbsp;=&nbsp;[0-9]&nbsp;onchange&nbsp;=&nbsp;checkpattern(this)&nbsp;placeholder="Enter&nbsp;Amount"&nbsp;onfocus="this.placeholder&nbsp;=&nbsp;''"&nbsp;onblur="this.placeholder&nbsp;=&nbsp;'Enter&nbsp;Amount&nbsp;'"&nbsp;required="">如果您想将其设置为数量(数字),则可以使用min和max:<input&nbsp;type&nbsp;=&nbsp;"number"&nbsp;name&nbsp;=&nbsp;"amt"&nbsp;min="5"&nbsp;max&nbsp;=&nbsp;"10"&nbsp;pattern&nbsp;=&nbsp;[0-9]&nbsp;onchange&nbsp;=&nbsp;checkpattern(this)&nbsp;placeholder="Enter&nbsp;Amount"&nbsp;onfocus="this.placeholder&nbsp;=&nbsp;''"&nbsp;onblur="this.placeholder&nbsp;=&nbsp;'Enter&nbsp;Amount&nbsp;'"&nbsp;required="">

拉丁的传说

您的代码中有很多问题,如果其他错误,并且您也没有正确传递输入值&nbsp;<script>function checkpattern(elem)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(elem<=10 && elem>=5)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; alert("5 to 10");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(!elem.match(/^\d+$/))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; alert('Accepts digits only');&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }</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="">
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript