如何在下面的代码中将onsubmit函数更改为onchange函数。如何在点击第二个日期而不点击提交按钮后立即显示当天的天数?
谢谢
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<script>
function dateDiff(dateform) {
date1 = new Date();
date2 = new Date();
diff = new Date();
date1temp = new Date(dateform.firstdate.value);
date1.setTime(date1temp.getTime());
date2temp = new Date(dateform.seconddate.value);
date2.setTime(date2temp.getTime());
diff.setTime(Math.abs(date1.getTime() - date2.getTime()));
timediff = diff.getTime();
days = Math.floor(timediff / (1000 * 60 * 60 * 24)+ 1);
dateform.difference.value = days;
return false;
}
</script>
</head>
<form onSubmit="return dateDiff(this);">
<pre>
First Date(MM/DD/YYYY): <input type=date name=firstdate>
Second Date(MM/DD/YYYY): <input type=date name=seconddate>
Date Difference (in days): <input type=text name=difference>
<input type=submit value="Calculate Difference!">
</pre>
</form>
</html>
答案 0 :(得分:0)
只需为表单提供一个ID <form onSubmit="return dateDiff(this);" id="myfrm">
在日期字段上分配更改处理程序并调用您的函数传递表单
<script>
var fd = document.querySelector("[name=firstdate]");
var sd = document.querySelector("[name=seconddate]");
var fm = document.querySelector("#myfrm");
fd.addEventListener('change',function(){ return dateDiff(fm); } );
sd.addEventListener('change',function(){ return dateDiff(fm); } );
</script>