Reputation: 23
Firstly, sorry English is not my first language.
*(Even and Odd is based on the index)
I would like to achieve this table in mobile view.
What i have tried
<table class="table">
<tbody>
<tr>
<th>Content 1 Head</th>
<th>Content 2 Head</th>
</tr>
<tr>
<td>Content 1</td>
<td>Content 2</td>
</tr>
</tbody>
<tbody>
<tr>
<th>Content 3 Head</th>
<th>Content 4 Head</th>
</tr>
<tr>
<td>Content 3</td>
<td>Content 4</td>
</tr>
</tbody>
</table>
var mobileTable = ""
$("table tbody th:even").each(function(i) {
var tdval = $(this).html();
console.log(thval);
mobileTable =+ "<th>" + $('table tr td:odd') + tdval +'</th>';
});
$('table:first-child').empty();
$('.table-mobile').append(mobileTable);
Upvotes: 2
Views: 97
Reputation: 4005
(index*2)
(((index+1)*2)-1)
append
.Your final array becomes:
[0] = th1
[1] = td1
[2] = th2
[3] = td2
...
var tarr = [];
$("table tr:even *").each(function(i) {
tarr[(i*2)]="<tr><th>"+$(this).html()+"</th></tr>";
});
$("table tr:odd *").each(function(i) {
tarr[((i+1)*2)-1]="<tr><td>"+$(this).html()+"</td></tr>";
});
console.log(tarr);
$('table').empty();
$('.table-mobile').append(tarr);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table">
<tbody>
<tr>
<th>Content 1 Head</th>
<th>Content 2 Head</th>
</tr>
<tr>
<td>Content 1</td>
<td>Content 2</td>
</tr>
</tbody>
<tbody>
<tr>
<th>Content 3 Head</th>
<th>Content 4 Head</th>
</tr>
<tr>
<td>Content 3</td>
<td>Content 4</td>
</tr>
</tbody>
</table>
<table class="table-mobile"></table>
Upvotes: 0
Reputation: 4915
var x = $("#table").find("th,td");
var i = $("#table").find("tr").length;
var j = x.length/i;
//console.log(i , j);
var newT= $("<table>").appendTo("body");
for (j1=0; j1<j;j1++){
//var temp = $("<tr>").appendTo(newT);
for(var i1=0;i1<i; i1++){
var temp = $("<tr>").appendTo(newT);
temp.append($(x[j1 *4+i1%2 *2+i1/2]).clone());
var temp2 = $("<tr>").appendTo(newT);
temp2.append($(x[j1 *4+i1%2 *2+i1/2+2]).clone());
//console.log(j1 *4,i1%2 *2,i1/2);
}
}
$("#table").remove();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="table">
<tbody>
<tr>
<th>Content 1 Head</th>
<th>Content 2 Head</th>
</tr>
<tr>
<td>Content 1</td>
<td>Content 2</td>
</tr>
</tbody>
<tbody>
<tr>
<th>Content 3 Head</th>
<th>Content 4 Head</th>
</tr>
<tr>
<td>Content 3</td>
<td>Content 4</td>
</tr>
</tbody>
</table>
Upvotes: 1
Reputation: 23
This is amendment made.
var mobileTable = ""
$("table tbody th").each(function(i) {
var thval = $(this).html();
var tdval = $('table tr td').html(); // How can i loop this through
mobileTable += "<tr><td>" + thval +'</td></tr><tr><td>'+ tdval + '</td><tr>';
});
$('table:first-child').empty();
$('.table-mobile').append(mobileTable);
Result (Triggered by jQuery)
Upvotes: 0