gpt4 book ai didi

javascript - Jquery 日期计算不适用于克隆

转载 作者:太空宇宙 更新时间:2023-11-04 11:26:55 25 4
gpt4 key购买 nike

目前正在使用 jquery 日期选择器计算从日期到日期的体验。例如(如果用户选择日期 01/05/2010 (from) - (To) 31/07/2013 -- result will be 3years and 3 months)结果将以标签格式显示.同样,当用户单击添加更多按钮时,将在此处生成多一行,用户还可以输入开始日期和结束日期。结果将是两行(如果用户选择日期 01/05/2010 (from) - (To) 31/07/2013 -- result will be 6years and 6 months)它有计算两行。

这是为当前计算编写的Jquery代码

   $(document).on('change', "#txt_Tdob", function (){
var date1 = document.getElementById("txt_Fdob").value;
var date2 = document.getElementById("txt_Tdob").value;
var x = date1.split("-");
var y = date2.split("-");
var fromdate = new Date(x[2], x[0] - 1, x[1]);
var todate = new Date(y[2], y[0] - 1, y[1]);
var diffDays = parseInt((todate - fromdate) / (1000 * 60 * 60 * 24));
var year = parseInt(diffDays / 365);
var date = diffDays - (365 * year);
var month = parseInt(date / 30);
document.getElementById("txt_expy").innerHTML = year + " year";
document.getElementById("txt_expm").innerHTML = month + " Month";
});

这是 fiddle updated fiddle

注意:根据这个 fiddle 链接,当用户第一次单击日期选择器时,只有当用户第二次单击“添加更多”按钮时,它才会起作用

请帮助我

感谢和问候马哈德万

最佳答案

好的,这是为您更新的代码,请注意 future 日期的验证尚未完成。我的意思是,如果您选择 future 的一年,它只会将其添加到总体体验中,并且您需要将代码精炼成更好的代码,因为它可能仍包含克隆的 id。我刚刚在这里展示了如何实现该功能。

DEMO

$(document).on('change', ".datepicker", function (){
//.datepicker is a common class for all datepickers and change in any datepicker will trigger this
var valid=true;//check if all the datepickers have been selected
$.each($('.datepicker'),function(){
if($(this).val()=="")//if any of datepickers value is null do not add
{
valid=false;//set valid to false and return
return false;
}
});
if(valid)//only if it is valid perform adding operation
{
var dateStart=[];//create an array to store startDate
var dateEnd=[];//and endDate
$.each($('.datepicker'),function(){
if($(this).hasClass('startDate')) //if the current control is startdate push it to corresponding array
dateStart.push($(this).val())
else
dateEnd.push($(this).val())
});
$.each($(dateStart),function(key,value){
var x = dateStart[key].split("-"); //get first startdate from array
var y = dateEnd[key].split("-"); //get first enddate from array
var fromdate = new Date(x[2], x[0] - 1, x[1]);
var todate = new Date(y[2], y[0] - 1, y[1]);
diffDays+= parseInt((todate - fromdate) / (1000 * 60 * 60 * 24));
//diffDays is now a global variable which is declared in document.ready.
//You can find it in fiddle
});
var year = parseInt(diffDays / 365);
var date = diffDays - (365 * year);
var month = parseInt(date / 30);
document.getElementById("txt_expy").innerHTML = year + " year";
document.getElementById("txt_expm").innerHTML = month + " Month";
//rest all things down here remains same.
}
});

HTML 已稍作更新。请检查 fiddle

关于javascript - Jquery 日期计算不适用于克隆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32305178/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com