簡體   English   中英

如何使輸入字段只接受200到500之間的數字?

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

我想輸入一個字段,用戶只能在該字段中輸入一個大於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> 

為什么不只是使用范圍呢?

 $('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> 

試試下面的代碼,

$('.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