Can't find why this js / jQuery to display last 12 months generates "undefined" warning

I am unable to get rid of the "undefined" message that is displayed in the html inside the ul tag and before the first li.

HTML:

<ul id="monthFilters" class="dropdown-menu pull-right" role="menu" aria-labelledby="dropdownMenu1"></ul>

      

JS / JQuery:

$(document).ready(function(){  
    var theMonths = new Array("01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12");
    var theMonthNames = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
    var today = new Date();

    var aMonth = today.getMonth();
    var aYear = today.getFullYear();

    var i;
    var monthList;

    for (i=0; i<12; i++) {

        monthList += '<li role="presentation"><a role="menuitem" tabindex="-1" href="?addedin=' + aYear + '-' + theMonths[aMonth] + '">'+theMonthNames[aMonth]+'</a></li>';

        aMonth--;

        if (aMonth < 0) {
            aMonth = 11;
            aYear--;
        } 
    }

    monthList += '<li role="presentation"><a role="menuitem" tabindex="-1" href="?all">Show All</a></li>';

    $("#monthFilters").append(monthList);

});

      

See the codepen error message . No errors are displayed in the console. Am I just too tired and missing something simple / silly?

+3


source to share


3 answers


You are not defining monthList as a string, so you are trying to add a string to undefined. Just do it in front of your loop



  var monthList = "";

      

+3


source


You need to initialize the variable monthList

. In your code it matters undefined

, so the <li>

word is added when the first element is created undefined

.

Initialize it with an empty string like



var monthList = "";

      

+2


source


Can you try this?

var monthList;

      

to

var monthList="";

      

0


source







All Articles