How to split column into row

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



How to split column into row



Ex: If i have obj with 6 data length. we know if we loop thats in table row, we will get 6 row and 1 column.
And now i want make thats loop, with my rules, if set 3 rules, so i will get 3 collums and 2 row, or if set 6 then get 6 columns and just 1 row



Hope someone can help



Thanks,




<!DOCTYPE html>
<html>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>

<h2>JavaScript Loops</h2>

<p id="demo"></p>
<table id="tbl" border="1px">
<tr id="tbl_tr"></tr>
</table>

<script>
var cars = ["BMW", "Volvo", "Saab", "Ford", "Fiat", "Audi"];
var text = "";
var i;
var row=$("#tbl_tr");
for (i = 0; i < cars.length; i++)
text +="<tr>";
text += "<td>"+cars[i] + "</td>";
text +="</tr>";

row.html(text);
//document.getElementById("demo").innerHTML = text;
</script>

</body>
</html>




2 Answers
2



In order to implement what you are trying to do, you need to implement a splitter logic which is easy to implement. You have to pass how many cells should be in a row if that particular point reached create a new row.



Check the snippet below:




var tblspliter = $('#tblspliter');
var spliterCell = $('#txtspliter');
var cars = ["BMW", "Volvo", "Saab", "Ford", "Fiat", "Audi"];

$('#btnsplit').on('click', function()

if (spliterCell.val() !== '')
tblspliter.empty(); //refreshing the table
let tbody = $('<tbody></tbody>');
let tr = $('<tr></tr>');
let appendedRow = 0;
for (let i = 0; i < cars.length; i++)
if (spliterCell.val() == appendedRow)
tbody.append(tr);
tr = $('<tr></tr>');
appendedRow = 0;

tr.append('<td>' + cars[i] + '</td>');
appendedRow++;

tbody.append(tr);
tblspliter.append(tbody);
else
alert('unable to split enter value');
);


<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<label for="txtspliter">Splitter Cell:</label>
<input type="number" id="txtspliter">
<input type="button" value="split" id="btnsplit">
</div>

<table id="tblspliter" border=1>

</table>



Just change the content of the looping.


for (i = 0; i < cars.length; i++)
if (i % 3 == 0) // add tr at the start of the row
text +="<tr>";

text += "<td>"+cars[i] + "</td>";
if (i % 3 == 2) // close tr at the end of the row. 2 is the biggest remainder when divide by 3
text +="</tr>";




I use modulo 3 to get 3 columns like you described.






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Firebase Auth - with Email and Password - Check user already registered

Dynamically update html content plain JS

Creating a leaderboard in HTML/JS