Sidney Sousa
Sidney Sousa

Reputation: 3584

Month prints undefined in jquery

Currently, I am able to select values from from option boxes and date. Then when I click on the anchor tag, I am able to pick all the data to form a url. However, when I see the url, the date comes as undefined. The following jquery code is what I used to pick the dates:

$("#dt1").datepicker({
    dateFormat: "dd-M-yy",
    minDate: 0,
    onSelect: function (date) {
        var dt2 = $('#dt2');
        var startDate = $(this).datepicker('getDate','+1d');
        startDate.setDate(startDate.getDate()+1); 
        dt2.datepicker('option', 'minDate', startDate);
        dt2.datepicker('setDate', startDate);
    }
});

$('#dt2').datepicker({  
    dateFormat: "dd-M-yy",      
});

$("li#weskus").on('click', function() {
    $(this).addClass('weskusClass');
    num = 1;
    console.log(num);
});

$('a#atributo').click(function() {
    var monthNames = [
        "Jan", "Feb", "Mar",
        "Apr", "May", "Jun", "Jul",
        "Aug", "Sep", "Oct",
        "Nov", "Dec"
      ];

    var date1 = $("#dt1").datepicker('getDate'),
        day_1  = date1.getDate(),  
        month_1 = date1.getMonth() + 1,              
        year_1 =  date1.getFullYear();

    var date2 = $("#dt2").datepicker('getDate'),
        day_2  = date2.getDate(),  
        month_2 = date2.getMonth() + 1,              
        year_2 =  date2.getFullYear(); 

    var where_in = $('.date-example-container li.weskusClass span.value-in').text();

    var where = $('.date-example-container li.selected span.value').text();
    var people = $('#search-pax :selected').val();

    if( num == 1 ){
        $('a#atributo').attr("href", "http://www.lekkeslaap.co.za/akkommodasie-in/"+where_in+"?q="+where_in+"&start="+day_1+"+"+monthNames[month_1]+"+"+year_1+'&end='+day_2+'+'+monthNames[month_2]+'+'+year_2+'&pax='+people);
        num = 0;
    }
    else if( num < 1 ){
        $('a#atributo').attr("href", "http://www.lekkeslaap.co.za/akkommodasie/"+where+"?q="+where+"&start="+day_1+"+"+monthNames[month_1]+"+"+year_1+'&end='+day_2+'+'+monthNames[month_2]+'+'+year_2+'&pax='+people);
    }   

});

Here my running snippet so you can test.

Upvotes: 0

Views: 30

Answers (1)

Hassan Imam
Hassan Imam

Reputation: 22524

Change your month_1 and month_2 to month_2 = date2.getMonth(), and month_2 = date2.getMonth(),. Javascript date month are 0 based,i.e. January is 0, february is 1, so on and so forth.

So, for the month of December, your month value will be 12 but monthNames array is 0 based, so the monthNames[month_1] will be undefined.

Upvotes: 1

Related Questions