1

I need to load items of an array to a varaible as string to use it dynamically in the page

var data = ["Sat 17 Jan", "Wed 14 Jan", "Wed 7 Jan"]
var str;

for (i = 0; i < data.length; i++) { 
    str = '<button class="btn btn-success">'+data[i]+'</button>';
}
console.log(str);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

What I am getting now is only the last button in the console as:

<button class="btn btn-success">Wed 7 Jan</button>

but I need to get

<button class="btn btn-success">Sat 17 Jan</button><button class="btn btn-success">Wed 14 Jan</button><button class="btn btn-success">Wed 7 Jan</button>

3 Answers 3

3

You need to append the every new button to the string and for that use +=.

var data = ["Sat 17 Jan", "Wed 14 Jan", "Wed 7 Jan"]
var str = "";

for (i = 0; i < data.length; i++) { 
    str += '<button class="btn btn-success">'+data[i]+'</button>';
}
console.log(str);

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks void this is working but when I try to present the str in the page I am getting undefined at the beginning! Can you please take a look at This Demo to see what is happening?
Try this bootply.com/4olbJlLNqm , you need to do var str = "" instead of just var str;
Sure I just had to wait for 10 minutes :-)
1

var data = ["Sat 17 Jan", "Wed 14 Jan", "Wed 7 Jan"];

console.log($.map(data, function(aDate){
  return '<button class="btn btn-success">'+ aDate +'</button>';
}).join(''));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Comments

0

You re-assign str every loop cycle. Try this:

str = str + "your html";

in your for loop

1 Comment

Why are you using longhand?? str += "your html" is much simpler

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.