I’m trying to generate the following html :
<div class="row"> <div class="col-md-3"></div> <div class="col-md-3"></div> <div class="col-md-3"></div> <div class="col-md-3"></div> </div> <div class="row"> <div class="col-md-3"></div> <div class="col-md-3"></div> <div class="col-md-3"></div> <div class="col-md-3"></div> </div> <div class="row"> <div class="col-md-3"></div> </div>
So I tried the following :
var response = '[{"id":7},{"id":10},{"id":15},{"id":11},{"id":14},{"id":9},{"id":8},{"id":12},{"id":1}]' var json = $.parseJSON(response); var add_html = ""; $(json).each(function (i, val) { if (i % 4 == 0){ add_html += "<div class='row'>"; } add_html = add_html + "<div class='col-md-3'></div>"; if (i % 4 == 0){ add_html = add_html + "</div>"; } }); /* if (i % 4 != 1){ add_html = add_html + "</div>"; } */ console.log(add_html)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
But doesn’t output the desired result
Advertisement
Answer
Try like below. And check changes with comment.
There are two changes in your code.
- You need to open your
row
div withi%4 == 0
and close it withi%4 == 3
. - Once
each
loop complete you should check if(json.length - 1) % 4 != 3
then need to add</div>
var response = '[{"id":7},{"id":10},{"id":15},{"id":11},{"id":14},{"id":9},{"id":8},{"id":12},{"id":1}]' var json = $.parseJSON(response); var add_html = ""; $(json).each(function(i, val) { if (i % 4 == 0) { add_html += "<div class='row'>"; } add_html = add_html + "<div class='col-md-3'></div>"; // Change 1 - Update condition here to compare with 3 if (i % 4 == 3) { add_html += "</div>"; } }); // Change 2 - Add additional condition if ((json.length - 1) % 4 != 3) { add_html += "</div>"; } console.log(add_html)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Old version
- Initialize
add_html
with opening row div. - When
i % 4 == 3
which means it is forth index add closing div and open a new one. - Once
each
loop completes then add closing div.
Note – This has one bug. It will add extra <div class='row'></div>
when json array is of json.length % 4 == 0
.
var response = '[{"id":7},{"id":10},{"id":15},{"id":11},{"id":14},{"id":9},{"id":8},{"id":12},{"id":1}]' var json = $.parseJSON(response); // Initialize your html with opening row div var add_html = "<div class='row'>"; $(json).each(function(i, val) { add_html = add_html + "<div class='col-md-3'></div>"; if (i % 4 == 3) { // <- Update condition here to compare with 3 // Close current row div and open new one add_html += "</div>"; add_html += "<div class='row'>"; } }); // End your html with closing row div add_html = add_html + "</div>"; console.log(add_html)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>