samtun
samtun

Reputation: 444

jquery array returning one undefined?

I am trying to get an array out of this html code to add boxes, having the numbers in their id, to my content:

<a href="#" data-box="38,39,40">An Array</a>

The boxes to add:

<div id="box38">
    ...
</div>
<div id="box39">
    ...
</div>
<div id="box40">
    ...
</div>

As there are also html lines like this:

<a href="#" data-box="24">No Array</a>

I also need something that detects if there are multiple values or just one. In this case I just used if (theid.length > 2) because the single values won't get longer then two characters.

The array should be [38,39,49] and it is, as console.log(theid); returns exactly this array.

var theid = $(this).data('box');
var newHTML = '';

if (theid.length > 2) {
    theid = theid.split(',');
    $.each(theid, function(idx) {
        newHTML += $('#box' + theid[idx]).html();
    });
} else {
    var newHTML = '';
    newHTML = $('#box' + theid).html();
    console.log(theid);
};

But if I then add newHTML to my existing content content.html(newHTML); there is always an "undefined" in front of the loaded boxes? Here's a screenshot:

enter image description here

Upvotes: 6

Views: 189

Answers (1)

Travis J
Travis J

Reputation: 82267

This is a byproduct of variable hoisting. Since you are using the += operator the string is being appended to the end of the variable newHTML which previously held undefined. You can look at it like this:

//hoisted
var newHTML = undefined;

var theid = $(this).data('box');

if (theid.length > 2) {
 theid = theid.split(',');
 $.each(theid, function(idx) {
    newHTML += $('#box' + theid[idx]).html();
 });
} else {
 /*var */newHTML = '';
 newHTML = $('#box' + theid).html();
 console.log(theid);
};

Upvotes: 3

Related Questions