peace_love
peace_love

Reputation: 6471

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".

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>

Upvotes: 0

Views: 81

Answers (3)

Jordec
Jordec

Reputation: 1564

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>

Upvotes: 1

Hany Alsamman
Hany Alsamman

Reputation: 501

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)
        })

    });

Upvotes: 1

Richard Parnaby-King
Richard Parnaby-King

Reputation: 14862

Use the number input field specifying the min/max.

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

Upvotes: 0

Related Questions