我希望从我的HTML流程中获取JS中的信息并将结果发送回HTML。在该示例中,JS计算人在住宿中的停留时间。我只需要办理入住和退房日期。
var date1 = new Date("7/13/2010");
var date2 = new Date("12/15/2010");
var timeDiff = Math.abs(date2.getTime() - date1.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
<form>
<p>Select your Check-in date please</p>
<input id="inDate" type="date">
</br>
<p>Select your Check-out date please</p>
<input id="outDate" type="date">
</br>
<span>You are staying</span><span id="stay"></span> <span> days with us.</span>
</br>
</form>
答案 0 :(得分:2)
获取“入住日期”:
var inDate=document.getElementById("inDate").value;
获取“退房日期”
var outDate=document.getElementById("outDate").value;
答案 1 :(得分:1)
如果您希望日期选择器只导入jquery UI库,它将允许您直接插入日期日历
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<form>
<p>Select your Check-in date please</p>
<input id="inDate" type="date">
</br>
<p>Select your Check-out date please</p>
<input id="outDate" type="date">
</br>
<span>You are staying</span><span id="stay"></span> <span> days with us.</span>
</br>
<link href="https://code.jquery.com/ui/jquery-ui-git.css" rel="stylesheet" type="text/css" />
<script src="https://code.jquery.com/jquery-git.js"></script>
<script src="https://code.jquery.com/ui/jquery-ui-git.js"></script>
</form>
</body>
</html>
添加以下javascript代码:
$(function() {
$( "#inDate, #outDate" ).datepicker();
});
以下是jsbin的链接:https://jsbin.com/kunugi/edit?html,js,output
答案 2 :(得分:0)
阅读代码评论,希望这会有所帮助
function calc() {
// get corresponding value from input
var inDate = document.getElementById('inDate').value;
var outDate = document.getElementById('outDate').value;
// allow calculations if both input fields have values, otherwise error can occur while calculating date
if (inDate && outDate) {
// convert to date format
var date1 = new Date(inDate);
var date2 = new Date(outDate);
// code for checking date1 > date 2 if you want
//calculations
var timeDiff = Math.abs(date2.getTime() - date1.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
//for Displaying in html
document.getElementById('stay').innerHTML = diffDays;
}
}
// adding event so that when we change any one of the field, the functuion will calculate the daydiff and display in the html page
document.getElementById('outDate').addEventListener("change", calc);
document.getElementById('inDate').addEventListener("change", calc);
&#13;
<form>
<p>Select your Check-in date please</p>
<input id="inDate" type="date">
<p>Select your Check-out date please</p>
<input id="outDate" type="date">
<span>You are staying </span><span id="stay"></span> <span> days with us.</span>
</form>
&#13;