每当input text
与今天相同时,我都会尝试更改$visa_expired
的颜色。但是现在,我收到一条错误Invalid Date
这是我的代码:
<script type="text/javascript">
function checkFilled() {
var today = new Date();
var expired = new Date("<?php echo $visa_expiry; ?> ");
var inputVal = document.getElementById("expiry");
if (inputVal.value == "") {
inputVal.style.backgroundColor = "red";
window.alert(today);
}
else{
inputVal.style.backgroundColor = "yellow";
}
}
checkFilled();
</script>
这是我的HTML:
<input type="text" class="form-control" size="5" value="$visa_expiry" id="expiry">
答案 0 :(得分:2)
这与我过去的做法相似
var inputElement = document.getElementById("expiry");
var inputDate = inputElement.value;
var expired = new Date();
var today = new Date();
expired.setUTCFullYear(inputDate.split("/")[2], inputDate.split("/")[0] - 1, inputDate.split("/")[1]);
if(today === expired) {
inputElement.style.backgroundColor = "red";
window.alert(today);
} else {
inputElement.style.backgroundColor = "yellow";
}
看起来你需要改变
<input type="text" class="form-control" size="5" value="$visa_expiry" id="expiry">
要
<input type="text" class="form-control" size="5" value="<?php echo $visa_expiry; ?>" id="expiry">
请注意,由于您使用的是输入表格框,因此总有可能会有人输入10-12-2016而不是您可能期望的10/12/2016格式。这将导致上述代码失败。你可能想考虑找一个datepicker,或者至少改变一下
<input type="text">
至
<input type="date">
然后创建一些代码以将日期格式化为您想要的内容。
参考
答案 1 :(得分:0)
如果2016年10月13日是$ visa_expiry的值,则不应该给出错误。 检查此链接并运行小提示它提醒日期。 http://phpfiddle.org/main/code/hpia-ub40
<script type="text/javascript">
function checkFilled() {
var today = new Date();
var expired = new Date("<?php echo $visa_expiry; ?> ");
var inputVal = document.getElementById("expiry");
if (today >= expired) {
inputVal.style.backgroundColor = "red";
}
else{
inputVal.style.backgroundColor = "yellow";
}
}
checkFilled();
</script>
答案 2 :(得分:-1)
您正在尝试在alert中显示Date对象,该对象需要输入字符串。您应该使用getDate()
代替。
试试这个:
var today = new Date();
var day = today.getDate();
var month = today.getMonth() + 1;
var year = today.getFullYear();
today = day + '/' + month + '/' + year