我有这个脚本 计算所选日期之间的天数
更新
此代码正确吗?如何在页面中显示循环?
$( document ).ready(function() {
$("#endDate").change(function () {
var date1 = new Date($("#startDate").val());
var date2 = new Date($("#endDate").val());
console.log(date2);
var timeDiff = Math.abs(date2.getTime() - date1.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
var dayes = $('#dayes').val(diffDays);
for( i=0;i<dayes; ++i ){
var checkbox = document.createElement('input');
checkbox.type = "checkbox";
checkbox.name = "name";
checkbox.value = "value";
checkbox.id = "id";
var label = document.createElement('label')
label.htmlFor = "id";
label.appendChild(document.createTextNode('text for label after checkbox'));
container.appendChild(checkbox);
container.appendChild(label);
}
});
});
<div class="col-lg-2">
<lable for="prodayes " style="font-size: 16px ; text-align: center" class="form-control rounded ">Event Dates </lable>
</div>
<div class="col-lg-2">
<input style="font-size: 16px ; text-align: center" class="form-control rounded " data-required="true" type="date" name="from_date" id="startDate" >
</div>
<div class="col-lg-2">
<lable for="prodayes " style="font-size: 16px ; text-align: center" class="form-control rounded ">TO </lable>
</div>
<div class="col-lg-2">
<input style="font-size: 16px ; text-align: center" class="form-control rounded " data-required="true" type="date" name="to_date" id="endDate" >
</div>
<div class="col-lg-2">
<lable for="prodayes " style="font-size: 16px ; text-align: center" class="form-control rounded "> Total Days </lable>
</div>
<div class="col-lg-2">
<input type="number" disabled id="dayes" value="" style="font-size: 16px ; text-align: center" class="form-control rounded ">
</div>
如何根据脚本结果创建复选框字段?
答案 0 :(得分:3)
只需将此代码添加到函数的末尾即可:
for (var i = 0; i < diffDays; i++) {
let elem = $('<div class="col-lg-2">');
elem.append($('<input class="form-control rounded" type="checkbox">'));
$("#dayes").insertBefore(elem);
}
这将在diffDays
之前的表格中插入#dayes
复选框。您的最终代码应如下所示:
$(document).ready(function() {
$("#endDate").change(function() {
var date1 = new Date($("#startDate").val());
var date2 = new Date($("#endDate").val());
console.log(date2);
var timeDiff = Math.abs(date2.getTime() - date1.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
$("#dayes").val(diffDays);
for (var i = 0; i < diffDays; i++) {
let elem = $('<div class="col-lg-2">');
elem.append($('<input class="form-control rounded" type="checkbox">'));
$("#dayes").insertBefore(elem);
}
});
});
答案 1 :(得分:2)
进行循环并按如下所示创建
var checkbox = document.createElement('input');
checkbox.type = "checkbox";
checkbox.name = "name";
checkbox.value = "value";
checkbox.id = "id";
var label = document.createElement('label')
label.htmlFor = "id";
label.appendChild(document.createTextNode('text for label after checkbox'));
container.appendChild(checkbox);
container.appendChild(label);