简体   繁体   中英

jQuery / javascript - correcting input min and max int not working correctly

I got this HTML:

<input type="number" name="eingangstuer_hoehe" min="70" max="200">

And this is the jQuery/javascript:

$("input").change(function(e) {
        var $this = $(this);
        var val = $this.val();
        var max = $this.attr("max");
        var min = $this.attr("min");


        if(val > min || val < max)
        {

        }
        else
        {
            if (val > max){
                e.preventDefault();
                $this.val(max);
            }

            if (val < min)
            {
                e.preventDefault();
                $this.val(min);
            }
        }
});

Typing 1 or 2 will not change anything. Typing 3 - 69 will work how it supposed to. Typing everything above 199 (yes also 200 ) will change the value to 70 ..

It also won't change the values above 600

You should use the condition as shown in the code snippet below.

Also You're compering string and not numbers. try parsing the values to integer with parseInt

your code should look like this:

    $("input").change(function(e) {
        var $this = $(this);
        var val = parseInt($this.val());
        var max = parseInt($this.attr("max"));
        var min = parseInt($this.attr("min"));

        if(val < min || val > max){
            e.preventDefault();
            $this.val(max);
        }
    }

});

Wrong condition found. Change if(val > min || val < max) to if(val >= min && val <= max)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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