2014-10-08 58 views
-1

有人可以幫我寫一個JavaScript函數,說明如果選擇的日期距離當前日期超過30天,那麼將20美元添加到我的費用計算器中?任何幫助將不勝感激我非常新的,不知道從哪裏開始我找不到甚至相似任何的例子..基於日期的函數以及計算費用

這是文本/日曆:

<cfinput 
     type="datefield" 
     name="purchasedate" 
     width="130" 
     required="yes" 
     message="Please enter purchase date." 
     value="#dateformat(now(),"mm/dd/yyyy")#" 
     > 

單選按鈕決定價格:

var title_prices = new Array(); 
title_prices["MCO"]=78.25; 
title_prices["FL Title"]=78.25; 
title_prices["OOS Title"]=88.25; 

function getProofOfOwnership() 
{ 
    var proofOfOwnership=0; 
    var theForm = document.forms["form"]; 
    var ownerShip = theForm.elements["ownership"]; 
    for(var i = 0; i < ownerShip.length; i++) 
    { 
     if(ownerShip[i].checked) 
     { 
     proofOfOwnership = title_prices[ownerShip[i].value]; 
     } 
    } return proofOfOwnership; 
} 

這需要的所有功能,並增加了費用一起:

function calculateTotal() 
{ 
    var titleFees = getProofOfOwnership() + (Function checking date); 
    var divobj = document.getElementById('totalPrice'); 
    divobj.style.display='block'; 
    divobj.innerHTML = "Estimated Transfer Fees $"+titleFees; 

} 

回答

1

釷是函數獲取日期參數,如果日期超過30天,則返回20;如果日期在30天或未來,則返回0。

function getDatePrice(date) { 
    if (Object.prototype.toString.call(date) !== '[object Date]') { 
     //If passed date is undefined or not valid, use today's date 
     date = new Date(); 
    } 

    var today = new Date(); 

    var diffMilli = today - date; 
    //Difference in milliseconds, need to convert to days 
    var diffDays = diffMilli * 1000 * 60 * 60 * 24; 

    if (diffDays > 30) { 
     return 20; 
    } 
    else { 
     return 0; 
    } 
} 

小提琴在行動:http://jsfiddle.net/rgjfwdpx/

編輯:爲配合你的代碼,你將需要檢索從標籤值。我對他們並不熟悉,但這是我如何去做的快​​速猜測。它可能不對。基本上你需要從輸入中獲取文本值,然後將其解析爲新的日期。

function calculateTotal() 
{ 
    //Get date from form. I've never worked with <cinput>, so this is just my guess 
    var theForm = document.forms["form"]; 
    var purchasedate = theForm.elements["purchasedate"]; 
    var date = new Date(purchasedate.value); 

    var titleFees = getProofOfOwnership() + getDatePrice(date); 
    var divobj = document.getElementById('totalPrice'); 
    divobj.style.display='block'; 
    divobj.innerHTML = "Estimated Transfer Fees $"+titleFees; 

} 
+1

日期參數是用戶選擇與當前日期相比較的日期。如果沒有提供日期,則使用當前日期,這意味着它將始終返回0,您沒有通過日期。 – hotforfeature 2014-10-09 00:45:40

+1

已更新我的回答 – hotforfeature 2014-10-09 14:01:01

+1

是否可以爲該函數上的日期設置格式? – 2014-10-10 18:40:43