Reputation: 833
I want to append every 3 records to one div in a for loop. numberList is dynamic so we are not sure of the exact length. requirement is that pick 3 records and wrap it in div. For example if numberList.length is 7 then we should have 3 divs. first 2 div will contain 3 records and last div will have one record.
How to go about this?
for (var j = 0; j < numberList.length; j++) {
number = numberList[j].Number;
}
after every 3 records, take the result and append in one div
Upvotes: 0
Views: 161
Reputation: 25527
<html>
<head>
<title>test</title>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.1.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var arr = ["one", "two", "three", "four", "five", "six", "seven"];
var j = 0;
var str = "";
var master = $("#masterDiv");
for (i = 0; i < arr.length; i++) {
str += arr[i];
j++;
if (j >= 3) {
master.append($('<div/>', { html: str }));
str = "";
j = 0;
}
}
master.append($('<div/>', { html: str }));
});
</script>
</head>
<body>
<div id="masterDiv"></div>
</body>
</html>
Upvotes: 1
Reputation: 263
-- Try This
var numberList = [10, 20, 30, 80, 50, 60 , 70 ,80,90,100,110,120,130];
var currentRecord = '';
var Num = 0;
var content = '';
for (var j = 0; j < numberList.length; j++) {
content = '';
Num = (j + 1);
if (Num % 3 == 0) {
currentRecord += numberList[j] + ' ';
$('#content').append('<div> newDiv '+ currentRecord+'</div>' );
currentRecord = '';
}
else {
currentRecord += numberList[j] + ' ';
}
if ((Num == numberList.length) && (Num % 3 != 0)) {
$('#content').append('<div>newDiv '+ currentRecord + '</div>' );
}
}
Upvotes: 1
Reputation: 76736
Try something like this:
var numberList = [ 123, 234, 345, 456, 567, 678, 789 ]; // sample data
var frag = document.createDocumentFragment(),
div;
for (var j = 0; j < numberList.length; j++) {
if (!(j % 3)) {
div = document.createElement('div');
frag.appendChild(div);
}
div.appendChild(document.createTextNode(' ' + numberList[j]));
}
document.body.appendChild(frag);
Example here: http://jsfiddle.net/vtQtr/
Most of this should look pretty familiar; you may want to read up on the remainder operator %
(sometimes called "mod" or "modulo") if you're not familiar with it.
We also use a document fragment to avoid repeatedly modifying the document. First, we insert things into the fragment, and then we insert the entire fragment into the document at once.
I separated the numbers in each div with a single space in this example, but you could adapt it to use anything you like.
Upvotes: 0
Reputation: 1988
You need something this?!
for (var j = 0; j < numberList.length; j++) {
if ((j+1)%3) {
// create new div
} else {
// add record to the div
}
}
Upvotes: 1