6

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

7
  • 2
    Where are you declaring newHTML before using it inside the each loop? Commented Jun 25, 2014 at 8:40
  • 4
    You're concatenating a new string to a previously undefined one. newHTML += "" means undefined += "" in your current code. Commented Jun 25, 2014 at 8:41
  • edited the newHTML declaration, sorry I missed it. Okay Melancia thats an interresting point... so I should try to define the newHTML wirth just = instead of += the first time? Commented Jun 25, 2014 at 8:44
  • The way your code looks now it's quite right, you can just remove the second declaration in your else condition. Commented Jun 25, 2014 at 8:45
  • Check @TravisJ answer below. Commented Jun 25, 2014 at 8:46

1 Answer 1

3

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);
};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.