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>
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();
}
}
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With