How to recreate a table dynamically in javascript - javascript

I am creating a table dynamically in a return statement from ajax. But I see only one row of the table, although debugger shows data.length as 4. How do I correct the recreating of table?
// using ajax return to recreate a table
// ...
if (data.length > 0) {
for (var i = 0; i < data.length; i++) {
var $mytablerow = $(
'<table>' +
'<tbody>' +
'<tr>' +
'<td id="td' + data[i].Value + '" >' +
data[i].Text +
'</td>' +
'</tr>' +
'</tbody>' +
'</table>'
);
}
}
var $mylst = $("#Userslist");
$mylst.html($mytablerow);
// ....

using ajax return to recreate a table
...
if (data.length > 0)
{
var $mytablerow = '<table><tbody>';
for (var i = 0; i < data.length; i++)
{
$mytablerow += $(
'<tr>' +
'<td id="td' + data[i].Value + '" >' + data[i].Text + '</td>' +
'</tr>');
}
$mytablerow += '</tbody></table>';
}
var $mylst = $("#Userslist");
$mylst.html($mytablerow);
....

I think you should use a variable outside the loop. For example:
if(data.length > 0) {
var $myTable = '<table><tbody>';
for (var i = 0; i < data.length; i++) {
$myTable += '<tr><td id="td' + data[i].Value + '" >' + data[i].Text + '</td></tr>';
}
$myTable += '</tbody></table>';
}
var $mylst = $("#Userslist");
$mylst.html($myTable);

You have problem in your script. To fix this problem replace by this script:
if (data.length > 0)
{
var $mytablerows = '<table>' + '<tbody>';
for (var i = 0; i < data.length; i++) {
$mytablerows += '<tr>' +
'<td id="td' + data[i].Value + '" >' + data[i].Text + '</td>' +
'</tr>';
}
$mytablerows += '</tbody>' + '</table>';
var $mylst = $("#Userslist");
$mylst.html($mytablerows);
}

That looks like you are creating a single row table each iteration and then only adding the last table you create. You need to create the table stuff once and then iterate to create the rows.

Related

table length in ajax table

var serial_no = 1;
if (response.length > 0) {
for (var count = 0; count < response.length; count++)
{
html += '<tr>';
html += '<td>' + response[count].id + '</td>';
html += '<td>€' + response[count].inkoopprijs + '</td>';
html += '<td>€' + response[count].verkoopprijs + '</td>';
html += '<td>' + response[count].producten + '</td>';
html += '<td><a href="../prijswijzigen.php?edit=' + response[count].id + '" class="edit_btn">Edit</td>';
html += '<td><a href="C_R_U_D.php?del=' + response[count].id + '" class="del_btn">Delete</td>';
html += '</tr>';
serial_no++;
}
} else {
html += '<tr><td colspan="3" class="text-center">No Data Found</td></tr>';
}
document.getElementById('post_data').innerHTML = html;
document.getElementById('total_data').innerHTML = response.length;
I have this for code for a data table, I made this to support a search function, but I can figure out how to set a table length. I want to set it to ten.

How to change span ID with each span created in loop

I have the following piece of code:
compareHtml += " </tr><tr>";
for (i = 0; i < compareArr.length; i++) {
compareHtml += '<td>' + compareArr[i].journaltitle + '</td>';
journalTitle.append('<span>' + compareArr[i].journaltitle + '</span> ');
}
And it creates a new span for each journalTitle. However, I want each new span to be created to have the ID "journalTitle1" "journalTitle2" "journalTitle3"....and so on.
Is this something that is possible? Currently they have no ID when created it is just a normal span.
You can do like following
compareHtml += " </tr><tr>";
for (i = 1; i < compareArr.length-1; i++) {
compareHtml += '<td>' + compareArr[i].journaltitle + '</td>';
journalTitle.append('<span id=journalTitle'+i+'>' + compareArr[i].journaltitle + '</span> ');
}

Dynamic Row addition to the Table

I want to add Array elements to the table.
Array elements are dynamic coming from the database. And i am creating the Row for adding the one row from the generated data and appending rowAfter to add the other array elements
Here is the code i have written -
var rowSpan = 0;
var rowSpan1 = 0;
for (element in data)
{
// get products into an array
var productsArray = data[element].products.split(',');
var QuantityArray = data[element].quantity.split(',');
var ChemistArray = data[element].Retailername.split(',');
var PobArray = data[element].Pob.split(',');
rowSpan = productsArray.length;
rowSpan1 = ChemistArray.length;
var row = '<tr>' +
'<td rowspan="'+rowSpan+'">' + data[element].date + '</td>'+
'<td rowspan="'+rowSpan+'">' + data[element].doctor_name + '</td>';
// loop through products array
var rowAfter = "";
for (var i = 0; i < rowSpan; i++) {
if(i == 0) {
row += '<td>' + productsArray[i] + '</td>';
row += '<td>' + QuantityArray[i] + '</td>';
} else {
rowAfter += '<tr><td>' + productsArray[i] + '</td><td>' + QuantityArray[i] + '</td>';
}
}
for (var k = 0; k < rowSpan1; k++) {
if(k == 0) {
row += '<td>' + ChemistArray[k] + '</td>';
row += '<td>' + PobArray[k] + '</td>';
} else {
rowAfter += '<td>' + ChemistArray[k] + '</td><td>' + PobArray[k] + '</td> </tr>';
}
}
row +=
'<td rowspan="'+rowSpan1+'">' + data[element].locations +'</td>'+
'<td rowspan="'+rowSpan1+'">' + data[element].area + '</td>'+
'</tr>';
$('#tbody').append(row+rowAfter);
So as per the code I can finely display ProductArray and Quantity Array
And But i am not able to display the Chemist array after one another.
In the above Image i want to display data( Kapila and Kripa below the Chemist column) Some where making issue with tr and td.
Any help would really appreciated.
Data is a JSON Response -
In my case, ChemistArray(Retailername in response) contains 4 names and POBArray 4 values.
You need to add an empty <td></td> as a "placeholder".
for (element in data) {
var productsArray = data[element].products.split(',');
var quantityArray = data[element].quantity.split(',');
var chemistArray = data[element].Retailername.split(',');
var pobArray = data[element].Pob.split(',');
// find the largest row number
var maxRows = Math.max(productsArray.length, quantityArray.length, chemistArray.length, pobArray.length);
var content = '';
var date = '<td rowspan="' + maxRows + '">' + data[element].date + '</td>';
var doctorName = '<td rowspan="' + maxRows + '">' + data[element].doctor_name + '</td>';
var locations = '<td rowspan="' + maxRows + '">' + data[element].locations + '</td>';
var area = '<td rowspan="' + maxRows + '">' + data[element].area + '</td>';
content += '<tr>' + date + doctorName;
for (var row = 0; row < maxRows; row++) {
// only add '<tr>' if row !== 0
// It's because for the first row, we already have an open <tr> tag
// from the line "content += '<tr>' + date + doctorName;"
if (row !== 0) {
content += '<tr>';
}
// the ternary operator is used to check whether there is items in the array
// if yes, insert the value between the <td></td> tag
// if not, just add an empty <td></td> to the content as a placeholder
content += '<td>' + (productsArray[row] ? productsArray[row] : '') + '</td>';
content += '<td>' + (quantityArray[row] ? quantityArray[row] : '') + '</td>';
content += '<td>' + (chemistArray[row] ? chemistArray[row] : '') + '</td>';
content += '<td>' + (pobArray[row] ? pobArray[row] : '') + '</td>';
// only add "locations + area + '</tr>'" if it is the first row
// because locations and area will span the whole column
if (row === 0) {
content += locations + area + '</tr>';
} else {
content += '</tr>';
}
}
$('#tbody').append(content);
}
content += '<td>' + (productsArray[row] ? productsArray[row] : '') + '</td>'; is just a short-hand for
content += '<td>';
if (productsArray[row]) {
content += productsArray[row];
} else {
content += '';
}
content += '</td>';
If there is item in the productsArray[row], let's say productsArray[0], which is 'Sinarest', then productsArray[row] would be truthy. Else, if there is no more products in the array, such as productsArray[3] will gives us undefined, which is a falsy value and the corresponding conditional will be ran.

Ajax Data Display fetched from Database

I have a data coming from the database. And Displaying when the ajax function is called. I am able to display it. But, One of the variable is an array data and saved it using implode function. Data is like (a,b,c,d).
Data is displaying in the below format
data1 Data2 Data3 (a,b,c,d) Data5 and so on.
I want to explode the array data and print one below the another.
I should display it like
data1 data2 data3 a data5
b
c
d
Here is the code which i am written to get the data.
<script type="text/javascript">
$('#genreport').on('click',function(){
var Representativeid = document.getElementById("Representativeid").value;
var dateFrom = document.getElementById("dateFrom").value;
var dateTo = document.getElementById("dateTo").value;
var url = '{{URL::to('/admin/GenReport')}}';
$.ajax({
type : 'get',
url : url,
data : {Representativeid:Representativeid,dateFrom:dateFrom,dateTo:dateTo},
success:function(data){
console.log(data);
var $tabledata = $('#tbody');
$tabledata.empty();
for (element in data)
{
var row = '<tr>' +
'<td>' + data[element].date + '</td>'+
'<td>' + data[element].doctor_name + '</td>'+
'<td>' #foreach(explode(',', data[element].products ) as $product)
{{$product}}
#endforeach '</td>' +
'<td>' + data[element].quantity + '</td>'+
'<td>' + data[element].locations +'</td>'+
'<td>' + data[element].area + '</td>'+
'</tr>';
$('#tbody').append(row);
}
},
error:function(data)
{
alert('fail');
alert(data);
}
});
});
</script>
I am failing in the for-each logic. Please help me to display as i expected.
You cannot use a php function/code(server-side) in your javascript/jQuery code(client-side), as the php code will be parsed before the page is loaded. Instead you need to use javascript code.
First, you need to split the value into an array
var productsArray = data[element].products.split(',');
then you would need to get the array count (.length) to use a rowspan, so it doesn't break your table stucture
var rowSpan = productsArray.length;
....
'<td rowspan="'+rowSpan+'">' + data[element].date + '</td>'+
....
finally, you need to loop in javascript, not php, through the array. (note, because the i<0 <td>s go on subsequent rows, you need to add them after)
var rowAfter = "";
for (var i = 0; i < rowSpan; i++) {
if(i == 0) {
row += '<td>' + productsArray[i] + '</td>';
} else {
rowAfter += '<tr><td>' + productsArray[i] + '</td></tr>';
}
}
so it would look something like this -
for (element in data)
{
// get products into an array
var productsArray = data[element].products.split(',');
// get products array count
var rowSpan = productsArray.length;
var row = '<tr>' +
'<td rowspan="'+rowSpan+'">' + data[element].date + '</td>'+
'<td rowspan="'+rowSpan+'">' + data[element].doctor_name + '</td>';
// loop through products array
var rowAfter = "";
for (var i = 0; i < rowSpan; i++) {
if(i == 0) {
row += '<td>' + productsArray[i] + '</td>';
} else {
rowAfter += '<tr><td>' + productsArray[i] + '</td></tr>';
}
}
row +=
'<td rowspan="'+rowSpan+'">' + data[element].quantity + '</td>'+
'<td rowspan="'+rowSpan+'">' + data[element].locations +'</td>'+
'<td rowspan="'+rowSpan+'">' + data[element].area + '</td>'+
'</tr>';
// append both row and the <td>s in rowAfter
$('#tbody').append(row+rowAfter);
}
just add <tr><td> inside foreach.
Edit:
Also, take a look at this link. table inside a td

Fill table in javascript with data from db

I have an html <table> that I need to fill with data from a database query. The query returns 10 rows and then sends the data to the method fill(data) to fill the table:
function getTopQ() {
alert("Get top Qs");
callServer('fill', 'checkConnection', false, 'SelectTopQues.php');
}
function fill(data) {
alert("ready to fill now");
$('#table').html('');
var search = '#table';
for (var i = 0; i < data.length; i++) {
$('#table').listview("refresh");
var Questions = data[i];
var str = '<td " ID="' + Questions[0] +
'" Question="' + Questions[1] +
'" UserID="' + Questions[2] +
'"CategoryId"' + '" SubCategoryId"' + '" DatePosted"' + '"';
str += '">'; //end li
str += '<a href="" data-transition="fade">';
str += Questions[1];
str += '</a>';
//str += '<span class="hiddenData">' + item[13] + '</span>';
str += '</td>';
$('#table').append(str);
$('#table').listview("refresh");
}
console.log(data);
console.log($('#table'));
$('#table').listview("refresh");
}

Categories

Resources