Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to accept only future or current time in input type='time'?

Tags:

html

jquery

I have an input field with type="time". How to make this field accept only the current or future time?

If the user enters a wrong time, a message should be displayed asking to enter the time again. Future here means upto 2 days.

Here I'm just displaying the current time using jquery.

function validDate(){
  var today = new Date().toISOString().split('T')[0];
  document.getElementsByName("date")[0].setAttribute('min', today);
}

$(function() {
  $('input[type="time"][value="now"]').each(function() {
    var d = new Date(),
        h = d.getHours(),
        m = d.getMinutes();
    if (h < 10) h = '0' + h;
    if (m < 10) m = '0' + m;
    $(this).attr({
      'value': h + ':' + m
    });
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body onload="validDate()">
    <div class="form-group">
      <p>Date<span>*</span></p>
      <input type="date" name="date" id="date" class="form-control input-sm " required />
    </div>
    <div>
      <p>Time <span>*</span></p>
      <input type="time" value="now" name="time" id="time" class="form-control input-sm " required />
    </div>
</body>
like image 537
coder7777 Avatar asked Jul 10 '17 10:07

coder7777


1 Answers

Here I give an simple solution. If both value are less than current value it will alert the user.

$(document).ready(function(){
            $("#time").on("focusout",function(e){
                var currentTime = new Date();
                var userTime = $("#time").val().split(":"); 
                if(currentTime.getHours() > parseInt(userTime[0])){
                    alert("To old value");
                    $(this).focus();                
                }
                if(currentTime.getHours() <= parseInt(userTime[0])){
                    if(currentTime.getMinutes() > parseInt(userTime[1])){
                        alert("To old value");
                    $(this).focus();
                    }
                }
            });
        });
like image 181
Ananth Cool Avatar answered Sep 28 '22 12:09

Ananth Cool