如果我从两个日期中选择,我想自动在文本框中显示总天数,但我无法得到它。如果我不使用Javascript,它就有效。如果没有使用Javascript,Datepicker
无法正常工作。我怎么能这样做?
这是我的剧本:
<input class="form-control" onchange="cal()" placeholder="Choose Date " type="text" id="example1" name="startdate" required="required" "/>
<input class="form-control" onchange="cal()" placeholder="Choose Date " type="text" id="example2" name="enddate" required="required" disabled="disabled" "/>
<input class="form-control" type="text" id="numdays2" name="total_leave"/>
这是java脚本:
<!--calendar Java script -->
<script type="text/javascript">
$(document).ready(function () {
$('#example1').datePicker({
format: "yyyy-mm-dd"
});
});
</script>
<!-- Datepicker -->
<script type="text/javascript">
$(document).ready(function () {
$('#example2').datePicker({
format: "yyyy-mm-dd"
});
});
</script>
<!-- calculate leave total day -->
<script type="text/javascript">
function GetDays(){
var dropdt = new Date(document.getElementById("example2").value);
var pickdt = new Date(document.getElementById("example1").value);
return parseInt((dropdt -(pickdt)) / (24 * 3600 * 1000))+1|| parseInt(1);
}
function cal(){
if(document.getElementById("example1")){
document.getElementById("numdays2").value=GetDays();
}
}
</script>
答案 0 :(得分:0)
您的代码中有很多位需要更改/修复,因此这是一个基于原始代码的工作示例。
<input class="form-control" placeholder="Choose Date " type="text" id="example1" name="startdate" required="required" />
<input class="form-control" placeholder="Choose Date " type="text" id="example2" name="enddate" required="required" />
<input class="form-control" type="text" id="numdays2" name="total_leave"/>
$(document).ready(function(){
$('#example1').datepicker({
format: "yyyy-mm-dd",
onSelect: function(){
cal()
}
});
$('#example2').datepicker({
format: "yyyy-mm-dd",
onSelect: function(){
cal()
}
});
});
function GetDays(){
var dropdt = new Date(document.getElementById("example2").value);
var pickdt = new Date(document.getElementById("example1").value);
return parseInt((dropdt -(pickdt)) / (24 * 3600 * 1000))+1|| parseInt(1);
}
function cal(){
if(document.getElementById("example1")){
document.getElementById("numdays2").value=GetDays();
}
}
答案 1 :(得分:0)
changeDate
事件
HTML
<input placeholder="Start Date " type="text" id="StartDate" />
<input placeholder="End Date " type="text" id="EndDate" />
<input type="text" id="datediff" />
JS
$('#StartDate,#EndDate').datepicker({
format: "yyyy-mm-dd",
autoclose: true,
});
$('#StartDate,#EndDate').datepicker().on('changeDate', function () {
if ($('#StartDate').val() != '' && $('#EndDate').val() != '') {
var date1 = new Date($('#StartDate').val());
var date2 = new Date($('#EndDate').val());
var timeDiff = date2.getTime() - date1.getTime();
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
$('#datediff').val(diffDays);
}
})