Search code examples
javascriptjqueryselectdatepickerselected

datepicker from - to and select x-value for set x-month later


I have an datepicker from - to. For the date -to i use an select value (stands for x month later). My code works only, f.e when i set a number like 6 (date.setMonth(date.getMonth() + 6 );). What is wrong?

My code is http://jsfiddle.net/uFcX7/3/

$(function (form) {
 var month = $('select[name=GetMes]').val();
 $(".fecha_inicio").datepicker({
     dateFormat: "dd/mm/yy",
     onSelect: function (dateText, instance) {
         date = $.datepicker.parseDate(instance.settings.dateFormat, dateText, instance.settings);
         date.setMonth(date.getMonth() + month);
         //date.setMonth(date.getMonth() + 6);

         $(".fecha_fin").datepicker("setDate", date);

     }
 });
 $(".fecha_fin").datepicker({
     dateFormat: "dd/mm/yy"
 });

});

When i use select value, the date are wrong.


Solution

  • This is because Javascript month has the range of 0 - 11. You would need to work out the difference and add a year. For instance:

    if((date.getMonth() + month) > 11)
    

    you will want to add 1 year to the date and then add the difference on months i.e.

    date.setMonth(date.getMonth() + (month - 11));