Oam Psy
Oam Psy

Reputation: 8663

Max attribute not respected when manually entering value

I have a input field for which I am trying to replicate hours in the day 0 - 24:

<input type="number" min="0" max="24" step="1" value="00" class="time-hours">
<input type="number" min="0" max="60" step="1" value="00" class="time-seconds">

When I click on the up/down chevrons, the max, and min I can go to are 24 and 0 as set in my attributes.

However, if I click on a cell, I can enter any number, e.g. 100.

How can I ensure only numbers between 0 and 24 can be entered?

Upvotes: 1

Views: 113

Answers (3)

SaidbakR
SaidbakR

Reputation: 13534

You can perform this pure JavaScript solution:

<script>
    ob = document.getElementById('f');
    ob.onblur = function(){

      if (ob.value*1 > ob.max*1 || ob.value*1 < ob.min*1){
        ob.value = 24
      }
    }
  </script>

Here you give the field an id. You are able to enclose it into a function to use it many fields.

Here is a demo

Upvotes: 1

Yatin Khullar
Yatin Khullar

Reputation: 1590

If you want to use javascript you can simple use this below code:

<input type="number" min="0" max="24" step="1" value="00" class="time-hours" onblur="return minmax(this.value);">
<input type="number" min="0" max="60" step="1" value="00" class="time-seconds" onblur="return minmax(this.value);">

<script>
    function minmax(val){
        if(val > 24 || val < 0){
            alert("Value cannot be grater than 24 and min than 0");
            return false;
        }
    }
</script>

I have used onblur because whenever value changes in two boxes they will trigger a function and it will check textbox value if value is greater than 24 or min than 0 it will prompt an alert.

I have used alert you can use anything for your validations.

I hope it will help you.

Upvotes: 1

Ahs N
Ahs N

Reputation: 8366

If its a form submit, the browser will stop the user. But in case you really need the validation, you can do this:

$(".time-hours").keyup(function() {
  if ($(this).val() > 24) {
    $(this).val("24");
  }
    if ($(this).val() < 0) {
    $(this).val("0");
  }
});

$(".time-seconds").keyup(function() {
  if ($(this).val() > 60) {
    $(this).val("60");
  }
    if ($(this).val() < 0) {
    $(this).val("0");
  }
});

Here is the JSFiddle demo

Upvotes: 1

Related Questions