如何在输入类型=“时间"中仅接受未来时间或当前时间? [英] How to accept only future or current time in input type='time'?
本文介绍了如何在输入类型=“时间"中仅接受未来时间或当前时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个带有type="time"
的input
字段.如何使该字段仅接受当前或将来的时间?
I have an input
field with type="time"
. How to make this field accept only the current or future time?
如果用户输入了错误的时间,则应显示一条消息,要求再次输入时间.这里的未来意味着最多2天.
If the user enters a wrong time, a message should be displayed asking to enter the time again. Future here means upto 2 days.
在这里,我只是使用jquery显示当前时间.
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();
}
}
});
});
这篇关于如何在输入类型=“时间"中仅接受未来时间或当前时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文