我需要在html页面的一个输入文本字段中设置日期,然后在设置日期后调用脚本并将新的日期值分配给另一个文本字段。使用第一个日期值计算新的日期值。
我使用$("#id").change()
。但它不像我预期的那样有效。这是我的代码。
<html>
<head>
<title>my file</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<!-- Load jQuery JS -->
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<!-- Load jQuery UI Main JS -->
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script>
$(function() {
$("#firstDate,#lastDate").datepicker({dateFormat: 'dd-mm-yy'});
});
</script>
<script>
$(document).ready(function() {
$("#firstDate").change(function(event) {
event.preventDefault();
var initialDate = ("#firstDate").val();
var totDate = initialDate;
var dateArray = totDate.split("-");
var dateObj = new Date(dateArray[2], dateArray[1] - 1, dateArray[0]);
dateObj.setDate(dateObj.getDate() + 14);
totDate = (dateObj.getDate() + 14) + "-" + dateObj.getMonth() + "-" + dateObj.getFullYear();
alert(totDate);
$("#lastDate").val(totDate);
});
});
</script>
</head>
<body>
<div>
first date: <input type="text" id="firstDate"/>
last date: <input type="text" id="lastDate" />
</div>
</body>
</html>
我已经将防止默认设置为停止页面在调用脚本后滚动到顶部(这是一个大html页面的一部分)。 为什么这不能正常工作。你能解释一下为什么没有这项工作以及克服这个问题的方法。
答案 0 :(得分:6)
正如我在评论中所说的那样,你的脚本中的问题是缺少$
但我会改变实现以使用datepicker api方法
$(document).ready(function() {
$("#firstDate").change(function(event) {
var dateObj = $("#firstDate").datepicker('getDate');
dateObj.setDate(dateObj.getDate() + 14);
$("#lastDate").val($.datepicker.formatDate('dd-mm-yy', dateObj));
});
});
$(function() {
$("#firstDate,#lastDate").datepicker({
dateFormat: 'dd-mm-yy'
});
});
&#13;
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.js"></script>
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/themes/redmond/jquery-ui.css">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.js"></script>
<div>
first date: <input type="text" id="firstDate"/>
last date: <input type="text" id="lastDate" />
</div>
&#13;