Javascript添加/删除值

时间:2014-08-22 10:19:44

标签: javascript jquery

我有这个JS代码:

$("#submit").on('click',function() {
    //work out number of days between the two dates
    var days_between = $("#todate").val() - $("#fromdate").val()

    //do the cost per month times 12 (months)
    var year_cost = $("#cost_per_month").val() * 12

    //do the yearly cost / 365
    var daily_cost = year_cost / 365
    var daily_cost = parseFloat( daily_cost.toFixed(2) )

    //now do the daily cost times cost_per_month
    var total_cost = daily_cost * days_between

    $(".total_days").html(days_between);
    $(".total_cost").html(total_cost);
})

我收到一个错误,说NaN。

我正在输入以下内容:

#from_date = 2014-08-19
#to_date = 2014-08-31
#cost_per_month = 2.60

4 个答案:

答案 0 :(得分:2)

计算数据之间天数的方式是错误的。看看这个 How do I get the number of days between two dates in JavaScript? 这可能会有所帮助!

答案 1 :(得分:1)

您尚未将文本框值解析为int:

var days_between = parseInt($("#todate").val()) - parseInt($("#fromdate").val())

var year_cost = parseInt($("#cost_per_month").val()) * 12

答案 2 :(得分:1)

这将工作

    //work out number of days between the two dates
var oneDay = 24 * 60 * 60 * 1000; 
//var date1 = new Date("2014,08,31");
//var date2 = new Date("2014,08,19");

var date1 = new Date("2014-08-31");
var date2 = new Date("2014-08-19");

var Daysd = date1.getDate() - date2.getDate();

    //var days_between = date1 - date2
    var diffDays = Math.round(Math.abs((date1.getTime() - date2.getTime()) / (oneDay)));

    //do the cost per month times 12 (months)
    var year_cost = parseInt(2.60) * 12

alert(Daysd);
alert(year_cost);

DEMO

答案 3 :(得分:0)

你不能直接得到总天数

   var tDate = new Date($("#todate").val());
    var fDate = new Date($("#fromdate").val());
    var diff=tDate-fDate;

    This would give you the difference in milliseconds between the two dates.

    var DaysNo= diff / 1000 / 60 / 60 / 24;