2014-10-06 40 views
1

我有這段html代碼,其中有兩個日期選擇器(輸入類型=「日期」)和一個文本框ID =「numdays」。我想計算兩個選定日期之間的天數,並在我的文本字段中顯示數字。我也想限制選擇比今天早的日期。我認爲這可以通過JavaScript或jQuery來完成。您的幫助將不勝感激。謝謝。計算兩個輸入類型=「日期」之間的天數在html中

<div id="reserve_form"> 

<div id="pickup_date"><p><label class="form">Pickup Date:</label><input type="date" class="textbox" id="pick_date" name="pickup_date" </p></div> 

<div id="dropoff_date"><p><label class="form">Dropoff Date:</label><input type="date" class="textbox" id="drop_date" name="dropoff_date"/></p></div> 

<div id="numdays"><label class="form">Number of days:</label><input type="text" class="textbox" id="numdays" name="numdays"/></div> 

</div> 
+4

您是否嘗試過... [東西](http://whathaveyoutried.com/)? – 2014-10-06 12:49:52

+0

對於日期時間管理和處理,我熱烈地建議你現有的庫。 Leverege對他們執行這種計算。我通常使用[moment.js](http://momentjs.com/)。 – 2014-10-06 12:51:17

+0

你的標記無效,''''pick_date'缺少' – 2014-10-06 12:52:05

回答

2

你可以這樣做。

<!DOCTYPE html> 
<html> 
<head> 
    <script type="text/javascript"> 
     function GetDays(){ 
       var dropdt = new Date(document.getElementById("drop_date").value); 
       var pickdt = new Date(document.getElementById("pick_date").value); 
       return parseInt((dropdt - pickdt)/(24 * 3600 * 1000)); 
     } 

     function cal(){ 
     if(document.getElementById("drop_date")){ 
      document.getElementById("numdays2").value=GetDays(); 
     } 
    } 

    </script> 
</head> 
<body> 
    <div id="reserve_form"> 

    <div id="pickup_date"><p><label class="form">Pickup Date:</label><input type="date" class="textbox" id="pick_date" name="pickup_date" onchange="cal()"</p></div> 

    <div id="dropoff_date"><p><label class="form">Dropoff Date:</label><input type="date" class="textbox" id="drop_date" name="dropoff_date" onchange="cal()"/></p></div> 

    <div id="numdays"><label class="form">Number of days:</label><input type="text" class="textbox" id="numdays2" name="numdays"/></div> 

    </div> 
</body> 

+0

當我選擇兩個日期時,如何讓它在文本框中自動顯示結果?謝謝 – Pravish 2014-10-06 13:16:07

+0

感謝您的幫助! 我編輯了部分代碼,當我更改日期時,天數差異顯示在文本框中。 – Pravish 2014-10-06 13:58:01

相關問題