Reputation: 397
I have this loop that creates List items and inserts that into a <ol>
element. It works very well, however, the first thing that it prints out is "undefined" inside the <ol>
(Not as a <li>
item though), and then the real <li>
items come afterwards.
var calculatedPayments
is a number from an input field
(like 5).
<ol id="month-list" class="list-group"></ol>
var i;
var monthsItem;
for (i=1; i <= calculatedPayments; i++) {
monthsItem += '<li class="list-group-item"> Månad '+i+':';
monthList.innerHTML = monthsItem;
console.log(i);
}
Upvotes: 0
Views: 83
Reputation: 6902
At the first iteration of your loop, your variable monthsItem
was not yet defined, and therefore, its value was mapped to undefined
when this line was called:
monthsItem += '<li class="list-group-item"> Månad '+i+':';
The fix: Initialize monthsItem
to be an empty string:
var monthsItem = "";
Upvotes: 1
Reputation: 59
Don't use + before = while assigning <li>
to monthsItem, it's concatenating value of monthsItem (which is undefined obvious ) with your <li>
snippet.
Just use simple assignment operator to assign like:
monthsItem = '<li class="list-group-item"> Månad '+i+':';
Upvotes: 2