Search code examples
javascriptdatepickermootools

mootools datepicker set value from other datepicker


I have a mootools datepicker (Arian / monkeyphysics) with 2 date input fields.
I want to set the date of the 2nd field one day after the first one.

So far I have:

window.addEvent("domready", function(e){
  new DatePicker('#arrival_date', { positionOffset: { x: -3, y: 5 }});
  new DatePicker('#departure_date', { positionOffset: { x: -3, y: 5 },onShow: function(){test();}
});

function test(){
  firstvalue = Date.parse($('arrival_date').value);
  newvalue = firstvalue.increment(); //ad 1 day to first input date
  console.log(newvalue); // Logs ok:Fri Jan 16 1970 22:24:11 ...

  $('arrival_date').set('value', newvalue );         //doesn't work
  $$('#departure_date').attach('#arrival_date');     //doesn't work
  $$('#departure_date').select(newvalue );           //doesn't work
}

How to do? (set the date of the 2nd field one day after the first one.)


Solution

  • That version of DatePicker uses hided inputs. So what you see is not what your input has as value, it has a unix datestamp.

    If you noticed the Date.parse($('arrival_date').value); was in the 70's, that's because javascript uses miliseconds and unix time is in seconds. To get the "real" day from the $('arrival_date').value you need to multiply by 1000. But you actually dont need that.

    To make the second DatePicker get the day from the first you can use this:

    onSelect: function (){
        var depDate = $('departure_date');
        if (depDate.value == ""){
            depDate.value = $('arrival_date').value + 86400;
        }
    }
    

    This will add one day to the first datepicker date if the second is empty. The thing is that you will not see the change until the you open the datepicker, so if you change the value programatically the user will not see. Which means that without the if, in case the user changes the first input again, you loose the second date and user doesn't notice, leading to frustration/bugs.