在提交表单后显示输出一秒钟后,我一直试图防止p标签中的结果和日期输入消失,因为稍后辅助程序无法从p标签中读取数据。
请帮助!
function Adate(){
var edate= document.getElementById("dob").value;
var res = document.getElementById("result");
var tday = new Date();
var bdate = new Date(edate);
var agedate= tday.getFullYear() - bdate.getFullYear();
if(agedate>=0)
{
res.textContent ="You are "+agedate ;
}
else
{
res.textContent ="You are from the future!!";}
}
<body>
<form onsubmit="return Adate()">
Enter your DOB:
<input type="date" id = "dob" >
<input type="submit" value ="submit">
</form>
<p id="result">
</p>
</body>
答案 0 :(得分:1)
只需将return false;
添加到函数Adate()
的末尾,就可以达到目的:
function Adate(){
var edate= document.getElementById("dob").value;
var res = document.getElementById("result");
var tday = new Date();
var bdate = new Date(edate);
var agedate= tday.getFullYear() - bdate.getFullYear();
if(agedate>=0)
{
res.textContent ="You are "+agedate ;
}
else
{
res.textContent ="You are from the future!!";}
return false;
}
<body>
<form onsubmit="return Adate()">
Enter your DOB:
<input type="date" id = "dob" >
<input type="submit" value ="submit">
</form>
<p id="result">
</p>
</body>
在这里return false;
基本上意味着该页面不会尝试将表单提交到某个后端,因此不会刷新页面。
答案 1 :(得分:0)
我的变体
var edate = document.getElementById("dob").value;
var res = document.getElementById("result");
var form = document.querySelector('form');
function Adate() {
var tday = new Date();
var bdate = new Date(edate);
var agedate = tday.getFullYear() - bdate.getFullYear();
if (agedate >= 0) {
res.textContent = "You are " + agedate;
} else {
res.textContent = "You are from the future!!";
}
setTimeout(function() {
form.submit();
},
4000
);
return false;
}
<form onsubmit="return Adate()">
Enter your DOB:
<input type="date" id="dob">
<input type="submit" value="submit">
</form>
<p id="result">
</p>