Reputation: 45
Really need as I struggled here but to no avail..start pulling my hair..Okay here's the scenario I have raw data from DB which is I wanna display in table.
but my problem is how to display the result in 4 columns and the new row is created after the columns=4 until end of record...I know how to done using PHP by using modulus but in Jquery..\0/ I have being struggle all days for now...
here's are my attempt
$.ajax({type :'GET',url : 'getalbums.php',dataType : 'json',
success : function(data){
$.each(data, function(i,item){
var lendata = data.length;
var columns = 2;
for(var i=0;i<lendata;i++){
if(i % columns == 0) {
$("<tr>").appendTo("#tablealbumphotos");
}
$("<td>YESSSS</td>").appendTo("#tablealbumphotos");
if((i % columns) == (columns - 1) || (i + 1) == lendata) {
$("</tr><tr><td>YESSSS</td></tr>").appendTo("#tablealbumphotos");
}
}
});
}
,error : function(XMLHttpRequest, textStatus, errorThrown) {
}
});
and here are my HTML
<table id="tablealbumphotos" class="tblphotos">
<!-- display the resutl here in grid format -->
</table>
Hope someone will shed me some light on how to goes for it..really need help..TQ
==================================EDITT===========================================
Thanks for the reply @olivieradam666
could you pls be more eloborate by this statements "Your server should send you an array of nbRows objects containing 4 fields (1 per column)." another things is your provide code will assign the result in grid regardless the total lenght of data eg:
col1 col2 col3 col4
col5 col6 col7 col8
col9 col10 undefined undefined
suppose to for total records of 10 and columns=4
col1 col2 col3 col4
col5 col6 col7 col8
col9 col10
Any hints tq
Upvotes: 0
Views: 505
Reputation: 4660
You could do this:
success : function(data){
var lendata = data.length;
var columns = 2;
for (var row = 0; row < lendata / columns; row++) {
var tr = $('<tr>').appendTo("#tablealbumphotos");
for (var i = 0; i < columns; i++) {
tr.append($("<td>YESSSS</td>"));//here you should use data[row*columns + i]
}
}
}
Upvotes: 2