简体   繁体   English

如何使输入字段只接受200到500之间的数字?

[英]How can I make an input field that only accepts numbers between 200 and 500?

I want to make an input field, where the user can insert only a number bigger than 200 and lower than 500. My problem is if I want to write for example "230" then the field doesn't allow me to, because it thinks I want to write "2". 我想输入一个字段,用户只能在该字段中输入一个大于200且小于500的数字。我的问题是,如果我想写例如“ 230”,则该字段不允许我输入,因为它认为我想写“ 2”。

 var t = false $('.myinput').focus(function () { var $this = $(this) t = setInterval( function () { if (($this.val() < 200 || $this.val() > 500)) { if ($this.val() < 200) { $this.val(200) } if ($this.val() > 500) { $this.val(500) } $('.error').fadeIn(1000, function () { $(this).fadeOut(500) }) } }, 50) }) $('.myinput').blur(function () { if (t != false) { window.clearInterval(t) t = false; } }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input class="myinput" type="number" value="200" min="200" max="500"> <p class="error" style="display:none">Accepting Only values 200-500</p> 

Why not just use a range? 为什么不只是使用范围呢?

 $('p').text($('input[type="range"]').val()); $('input[type="range"]').on('change', function(){ val = $('input[type="range"]').val(); $('p').text(val); }); 
 <script src="http://code.jquery.com/jquery-3.1.1.js"></script> <input type="range" min="200" max="500"/> <p></p> 

try the below code , 试试下面的代码,

$('.myinput').keypress(function(event){

        if(event.which != 8 && isNaN(String.fromCharCode(event.which))){
            event.preventDefault(); //stop character from entering input
        }
        var value = $(this).val();

        if (value > 200 && value < 500) { // check numbers between 200 and 500
            ..
        }

        $('.error').fadeIn(1000, function () {
            $(this).fadeOut(500)
        })

    });

使用number输入字段指定最小/最大。

 <input type="number" min="200" max="500" /> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM