如何防止结果,并输入数据从使用形式消失在Javascript提交[复制]

问题描述 投票:1回答:2

这个问题已经在这里有一个答案:

我一直在努力,以防止结果在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>
javascript html html5
2个回答
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;基本上意味着页面不会尝试提交表单一些后端,因此它不会刷新页面。


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>
© www.soinside.com 2019 - 2024. All rights reserved.