HTML Number Input Min and Max Not Working Properly

HTML number input min and max not working properly

With HTML5 max and min, you can only restrict the values to enter numerals. But you need to use JavaScript or jQuery to do this kind of change. One idea I have is using data- attributes and save the old value:

$(function () {  $("input").keydown(function () {    // Save old value.    if (!$(this).val() || (parseInt($(this).val()) <= 11 && parseInt($(this).val()) >= 0))    $(this).data("old", $(this).val());  });  $("input").keyup(function () {    // Check correct, else revert back to old value.    if (!$(this).val() || (parseInt($(this).val()) <= 11 && parseInt($(this).val()) >= 0))      ;    else      $(this).val($(this).data("old"));  });});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script><input type="number" min="0" max="23" value="14" />

HTML5 input number min max not working with required

This is the expected behaviour because FF21 doesnt supports min,max attribute...

you can check it in http://html5test.com/

Check the screenshot
Sample Image

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

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

});

The min-length of input is not working properly in this code

You can apply style on input based on the required minlength attribute or you can attach an invalid event handler on input.

input:invalid{
color:red;
border-color:red;
}
<input type="text" oninvalid="alert('Please enter atleast 3 charcater in name field');"  required minlength="3">


Related Topics



Leave a reply



Submit