Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 906
samtun Avatar asked Jun 25 '14 08:06

samtun


1 Answers

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);
};
like image 158
Travis J Avatar answered Nov 15 '22 06:11

Travis J