我有一个模糊功能,可以按日期选择器检查两个日期。如果结束日期早于开始日期,则会提示错误,并且所选日期无法填写在输入字段中。首先触发模糊事件:
...date picker
onSelect: function() {
this.focus();
},
onClose: function() {
this.blur();
}
...验证零件
jQuery("#p_stdy_edate").blur(function() {
var stdy_bdate = jQuery("#p_stdy_sdate").val();
var stdy_edate = jQuery("#p_stdy_edate").val();
if (stdy_edate < stdy_bdate) {
alert("End date should be later than begin date");
}
});
但是,当我选择一个无效的结束日期时(结束日期输入框有一个默认日期),在显示警报后,无效的日期会填入输入字段。如何解决?
答案 0 :(得分:1)
在显示警报后,您可以将edate的值强制为无效输入之前的值。例如:
jQuery("#p_stdy_edate").blur(function() {
var stdy_bdate = jQuery("#p_stdy_sdate").val();
var stdy_edate = jQuery("#p_stdy_edate").val();
if (stdy_edate < stdy_bdate) {
alert("End date should be later than begin date");
$("#p_stdy_edate").val("Please Select Ending Date");
}
});
如果“默认值”是您的默认值,则可以修改它。我也将聚焦作为事件而不是模糊(以这种方式使用模糊会导致我的经验错误)。使用focusout和validate可能会更好(特别是如果动态设置值,则希望用户的焦点在以编程方式更改值时不触发用户验证)。
-编辑;通过更改事件使一切变得更加容易;请测试以下代码:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css" integrity="sha384-Smlep5jCw/wG7hdkwQ/Z5nLIefveQRIY9nfy6xoR1uRYBtpZgI6339F5dgvm/e9B" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.8.0/css/bootstrap-datepicker.css" />
<title>Ilan's Test</title>
</head>
<body>
<div class="container">
<div class="row">
<div class='col-sm-12'>
<div class="form-group">
Start Date : <input id="sdate" class="form-control" type="text" /><br />
End Date : <input id="edate" class="form-control" type="text" /><br />
</div>
</div>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/js/bootstrap.min.js" integrity="sha384-o+RDsa0aLu++PJvFqy8fFScvbHFLtbvScb8AjopnFD+iEQ7wo/CG0xlczd+2O/em" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.8.0/js/bootstrap-datepicker.min.js"></script>
<script type="text/javascript">
$(function(){
$('#sdate').datepicker({
dateFormat: 'dd-mm-yy',
altField: '#thealtdate',
altFormat: 'yy-mm-dd'
});
$('#edate').datepicker({
dateFormat: 'dd-mm-yy',
altField: '#thealtdate',
altFormat: 'yy-mm-dd'
});
$('#edate').on('change',function () {
var sdate = $('#sdate').val();
var edate = $('#edate').val();
var diff = new Date(new Date(edate) - new Date(sdate));
var days = diff/1000/60/60/24;
if(days < 0){
alert("Sorry! You must pick an end date that is greater!");
$('#edate').val('');
} else {
alert ("This date range is good! Your start date and end dates are " + days + " days apart!");
}
return false;
});
});
</script>
</body>
</html>