0

I have two input fields with date1 and date2.Below this two fields i need a button that when i press it, will create a number of input fields equal to the number of months between the 2 date fields. For example i have date1=2012-03-21 and dat2=2012-06-21. It should generate 3 input fields Can you help me with this one?

jzworkman
  • 2,695
  • 14
  • 20
bizkit1
  • 23
  • 1
  • 7

2 Answers2

1

Let's assume the HTML looks something like this:

<div id="dateRange">
    <input type="text" id="startDate">
    <input type="text" id="endDate">
</div>
<div id="monthlyEntries"/>

Now, a month is not a uniform number of days ("30 days has September, April, June,and November..."), so I'm guessing the day portion of the dates don't matter.

Then, the javascript to call on change (or clicking a button, or whatever), would look something like this:

function buildMonthlyEntries() {
    var startDate = new Date(document.getElementById('startDate').value);
    var endDate = new Date(document.getElementById('endDate').value);
    if(startDate == "Invalid Date" || endDate == "Invalid Date") { return null; }
    var entryCount = (endDate.getMonth() + endDate.getFullYear()*12) - (startDate.getMonth() + startDate.getFullYear()*12);
    var monthlyEntries = document.getElementById('monthlyEntries');
    monthlyEntries.innerHTML = "";
    for(var i = 0; i < entryCount; i++) {
        var textElement = document.createElement('input');
        textElement.setAttribute('type', 'text');
        textElement.setAttribute('id', 'entry' + i);
        monthlyEntries.appendChild(textElement);
    }
    return null;
}
  • one problem, if i add different year it doesn`t generate the corect number of input fields. Can this script be modified to also calculate if i change the year? Thanks! – bizkit1 Mar 22 '12 at 07:08
0

You can run a loop based upon the difference in the dates. In pseudo code it would be something like

var difference = month2 - month1;

for(x=0;x<difference,x++){
     add inputfield;
}
Robert H
  • 11,520
  • 18
  • 68
  • 110
  • it would be very usefull to me a complete answer because i don`t know javascript very good – bizkit1 Mar 21 '12 at 19:16
  • Please check out http://stackoverflow.com/questions/4944750/how-to-subtract-date-time-in-javascript or http://stackoverflow.com/questions/674721/how-do-i-subtract-minutes-from-a-date-in-javascript or http://www.javascriptkit.com/javatutors/datedifference.shtml or search google for javascript date subtract for a ton of results. – Robert H Mar 21 '12 at 19:22