jquery append dynamic data in tr - javascript

I'm trying to print my dynamic data in table, i can get my data but tr part in tbody has issue
each one of this data should show in separate tr but they all print in 1 tr only.
This is the code of my issue part
var jqrajdate = '';
var jqrajtime = '';
var jqrajcity = '';
var jqrajdescription = '';
$.each(manifest, function(key3, value3) {
jqrajdate += value3['manifest_date'];
jqrajtime += value3['manifest_time'];
jqrajcity += value3['city_name'];
jqrajdescription += value3['manifest_description'];
});
$('div#proccess').append(
'<div class="mb-20"><h4>Riwayat pengiriman</h4></div>'+
'<table id="table" class="table table-bordered table-hover table-responsive">'+
'<thead>'+
'<th class="text-center">Tanggal</th>'+
'<th class="text-center">Jam</th>'+
'<th class="text-center">Kota</th>'+
'<th class="text-center">Keterangan</th>'+
'</thead>'+
'<tbody>'+
'<tr>'+
'<td class="text-center">'+jqrajdate+'</td>'+
'<td class="text-center">'+jqrajtime+'</td>'+
'<td class="text-center">'+jqrajcity+'</td>'+
'<td class="text-center">'+jqrajdescription+'</td>'+
'</tr>'+
'</tbody>'+
'</table>'
);
Can anyone help me with fixing my tr issues?

I assume that your manifest is an array of objects, containing the keys manifest_date, manifest_time, and etc. In this case, you are doing it incorrectly because you are concatenating/collapsing all values into a single variable and then printing a single <tr> element. What you need to do is to move all that logic into the the $.each() loop instead.
You don't actually have to use .$each(), using a normal Array.prototype.forEach() should work. What you need to do is:
Create the necessary markup, but leave the <tbody> element empty
Since you are using the same keys to access the data, you can pre-declare them in an array to be used later
Loop through all entries in manifest. For each data row, you:
Create a new <tr> element
Loop through the keys (see step 2), and for each key you access, you create a new <td> element and append it to the ` element
Once you're done, append the <tr> element to your table's <tbody> element
See sample code below:
// 1. Create the markup and empty table beforehand
$('div#process').append('<div class="mb-20"><h4>Riwayat pengiriman</h4></div>'+
'<table id="table" class="table table-bordered table-hover table-responsive">'+
'<thead>'+
'<th class="text-center">Tanggal</th>'+
'<th class="text-center">Jam</th>'+
'<th class="text-center">Kota</th>'+
'<th class="text-center">Keterangan</th>'+
'</thead>'+
'<tbody></tbody>'+
'</table>');
// 2. Loop through all entries in your array
var keys = ['manifest_date', 'manifest_time', 'city_name', 'manifest_description'];
manifest.forEach(function(row) {
var $row = $('<tr />');
keys.forEach(function(key) {
$row.append('<td>' + row[key] + '</td>');
});
$('#table tbody').append($row);
});
Proof-of-concept example:
// Dummy data
var manifest = [{
'manifest_date': 'date1',
'manifest_time': 'time1',
'city_name': 'city1',
'manifest_description': 'Lorem ipsum dolor sit amet 1'
}, {
'manifest_date': 'date2',
'manifest_time': 'time2',
'city_name': 'city2',
'manifest_description': 'Lorem ipsum dolor sit amet 2'
}, {
'manifest_date': 'date3',
'manifest_time': 'time3',
'city_name': 'city3',
'manifest_description': 'Lorem ipsum dolor sit amet 3'
}];
// 1. Create the markup and empty table beforehand
$('div#process').append('<div class="mb-20"><h4>Riwayat pengiriman</h4></div>' +
'<table id="table" class="table table-bordered table-hover table-responsive">' +
'<thead>' +
'<th class="text-center">Tanggal</th>' +
'<th class="text-center">Jam</th>' +
'<th class="text-center">Kota</th>' +
'<th class="text-center">Keterangan</th>' +
'</thead>' +
'<tbody></tbody>' +
'</table>');
// 2. Loop through all entries in your array
var keys = ['manifest_date', 'manifest_time', 'city_name', 'manifest_description'];
manifest.forEach(function(row) {
var $row = $('<tr />');
keys.forEach(function(key) {
$row.append('<td>' + row[key] + '</td>');
});
$('#table tbody').append($row);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="process"></div>

Related

Print every record of loop in a separate page in ajax success

How to print every record of loop in a separate page, While getting data through ajax and PHP in array. i.e
I want row1 data in every page, And row2 data every record in a separate page.
Trying the following script, not giving the desired result.
var response = {
row1: [{group: 'Group A'}],
row2: [
{team: 'Team A', player: 'Jema', result: 43},
{team: 'Team B', player: 'Deno', result: 34},
{team: 'Team B', player: 'Niob', result: 56},
{team: 'Team B', player: 'Skion', result: 49},
],
};
$("#group").html(response.row1.group);
var cats = {};
response.row2.forEach(function(element) {
cats[element.team] = cats[element.team] || [];
cats[element.team].push(element);
});
Object.keys(cats).forEach(function(team) {
let html = '';
html = '<tr>';
html += '<td>' + team + '</td>';
html += '</tr>';
$('table').append(html);
// Loop through the results for this category
cats[team].forEach(function(element) {
var names = element.player;
var result = element.result;
html = '<tr>';
html += '<td>' + names + '</td>';
html += '<td><input type="text" value="' + result + '"></td>';
html += '</tr>';
$('table').append(html);
});
// Append the textarea at the end of the results
html = '<tr>';
html += '<td><textarea placeholder="textarea..."></textarea></td>';
html += '</tr>';
$('table').append(html);
});
var PrintThis = document.getElementById('print');
var PrintStyle = '<style type="text/css">' +
'#media print{' +
'.Break { page-break-after: always }' +
'}' +
'</style>';
PrintStyle += PrintThis.innerHTML;
myWin = window.open("");
myWin.document.write(PrintStyle);
myWin.print();
myWin.close();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js"></script>
<div id="print">
<h1 id="group">
</h1>
<table class="table bordered">
<thead>
<th>Name</th>
<th>Result</th>
</thead>
<tbody>
</tbody>
</table>
</div>
JSFIDDLE of current output
See this example https://jsfiddle.net/qa9wcuft/ there is a break made in a div. It works at least in chrome Version 64.0.3282.167 and Firefox V 61.0.1. The problem is this: https://jsfiddle.net/rz3896se/ it works in firefox but not in chrome. It seems that chrome does not break tables. So my recommendation is to do different tables and put a div in the middle with a break, like this https://jsfiddle.net/8L201zvw/.
Also you are adding this: .Break { page-break-after: always } (.break is better) which is correct to separate pages, but you don't have any element with that class. My suggestion is that you should add class="break" (both in lowercase is better) in the last element you want in the page, in this case, I think is this:
html = '<tr class="break">';
html += '<td><textarea placeholder="textarea..."></textarea></td>';
html += '</tr>';
This does not work in chrome. My suggestion:

Get one specific row in automatically generated table

I am building a web application for the school. And I need to populate a table with data from a database. To do so, I used the following javascript :
http.onload = function (){
var roomData = JSON.parse(this.response);
roomData.forEach(data => {
var location=data.location;
var price=data.price;
var size=data.size;
var available=data.available;
var index = $("table tbody tr:last-child").index();
var row = '<tr>' +
'<td>'+location+'</td>' +
'<td>'+size+'</td>' +
'<td class="price">'+price+'</td>' +
'<td>'+available+'</td>' +
actions +
'</tr>'
$("table").append(row);
});
console.log((roomData));
}
http.open('GET', url, true);
http.send();
With the following architecture for the table :
<table class="table table-bordered">
<thead>
<tr>
<th>Address</th>
<th>Size</th>
<th>Price</th>
<th>Available</th>
</tr>
</thead>
<tbody>
</tbody></table>
But then, when I try to access one specific data with javascript, for example the price, I cannot really make the distinction between the rows because they have all the same id. Here is the code I am using to get the row's price :
$('td.price').html());
But obviously it only returns the price of the first row and not the one I want. How can I do it ?
You can achieve it as below:
Add the index in your forEach and use it as Id of the row:
roomData.forEach(function (element, index) {
var location=data.location;
var price=data.price;
var size=data.size;
var available=data.available;
var index = $("table tbody tr:last-child").index();
var row = '<tr>' +
'<td>'+location+'</td>' +
'<td>'+size+'</td>' +
'<td id="pricerow' + index + '" class="price">'+price+'</td>' +
'<td>'+available+'</td>' +
actions +
'</tr>'
$("table").append(row);
$('#pricerow1').html());
$('#pricerow2').html());
Ok I finally figured how to do it, I used :
var rows = document.getElementsByTagName('tr');
console.log(rows[$(this).closest("tr").index()+1].cells[2].innerHTML);
Your 'roomdata' info should have an ID of some sort, which you can use as an ID on the . Like (roomdata ID 5), en then access it with $('#rd-5 td.price').
Not sure if I understand you correctly, but that's the easiest way. Always have an unique reference and work with ID's.

how to put each inside append? [duplicate]

This question already has answers here:
How to use jQuery each() function within append()
(2 answers)
Closed 4 years ago.
Here is my code
$('#payment_detail').append(
'<table class="table table-bordered table-striped">'+
'<thead>'+
'<th>Payment Date</th>'+
'<th>Payment Value</th>'+
'<th>Verified By</th>'+
'</thead>'+
'<tbody>'+
$.each(response.payments, function (key, value) {
return '<td>'+ value.payment_date +'</td> <td>'+ value.payment_value +'</td> <td>'+ value.created_by +'</td>'
})+
'</tbody>'+
'</table>'
);
but the view looks like this
can someone help me? thanks
try this
('#payment_detail').append(
'<table class="table table-bordered table-striped">'+
'<thead>'+
'<th>Payment Date</th>'+
'<th>Payment Value</th>'+
'<th>Verified By</th>'+
'</thead>'+
'<tbody id="dtDetails"></tbody></table>');
$.each(response.payments, function (key, value) {
$("#dtDetails").append('<tr><td>' + value.payment_date + '</td> <td>' + value.payment_value + '</td> <td>' + value.created_by + '</td></tr>');
});

How to append table head only once when loop through the JSON

How to only once append table head when looping(search) through the JSON array?When I try this, every time when starting search table-head append for every match, although two products belong the same group.
HTML
</select>
Search: <input type="text" name="search" id="search" />
<div id="place"></div>
Java Script
$.ajaxSetup({ cache: false });
$('#search').keyup(function(event){
$('#place').html('');
if (event.keyCode == 8) {
$('#place').hide('')
}else{
$('#place').show('')
}
$('#state').val('');
var searchField = $('#search').val();
var expression = new RegExp(searchField, "i");
LOOP JSON
$.getJSON('product.json', function(result) {
//LOOP JSON
TABLE HEAD to appears only once in the search.
$.each(result, function(key, value){
//TABLE HEAD this need to apperas only one
var text = '';
text +='<table class="table" width="610" cellpadding="3"
cellspacing="1" bgcolor="#cccccc">';
text +='<tr>';
text +='<th width="20%" bgcolor="#aaaaaa" align="left"><font
color="#ffffff">Model</font></th>';
text +='<th width="25%" bgcolor="#aaaaaa"><font color="#ffffff">CODEC
Supported</font></th>';
text +='</tr>';
text +='<p style="font-size:15px; font-weight:bold; color:#2773ba;
margin-bottom:5px">'+value.brand+'</p>';
// END TABLE HEAD
//END OF TABLE HEAD -START TABLE BODY
// TABLE BODY is filling with data from json
if (value.brand.search(expression) != -1 ||
value.model.search(expression) != -1 ||
value.CODECSupported.search(expression) != -1 )
{
text += '<tr>'
text += '<td colspan="9" align="left" bgcolor="#FFFFFF" style="font-
weight:bold; color:#3399cc">'+value.type+'</td>'
text += '</tr>'
text += '<tr>'
text += '<td bgcolor="#FFFFFF">'+value.model+'</td>'
text += '<td align="center"
bgcolor="#FFFFFF">'+value.CODECSupported+'</td>'
text += '</tr>'
text += '</table>'
$('#place').append(text)
}
});
});
});
END OF BODY
})
You can either do the table creation outside of the loop (have just the generated data inside the loop), or you can have a boolean that checks whether you have went through the loop once
Example pseudo-ish code:
passed = false;
for(i=0;i<10;i++){
// some code happening
if(!passed){
// here add the headers
passed = true;
}
else{
//do the rest
}
// other code happening
}
I would recommend having the table setup outside the loop since it would be more efficient, because with this pseudo code you will have an extra check on each iteration of the loop.
Hope this helps!

Adding a for loop inside jQuery append method

I am having a table into which most elements are static.I however I have one <tr></tr> that i want to change dynamically using a for loop.I have only been able to add a for loop that updates everything in the table.
for(var x = 0; x< foo.length; x++){//Move the for loop from here
$("div#show_details").append('<table class="'+receipt_no+'" id="print_me" style="background:#ffffff;width:800px;font-family:Roboto;text-align:center;">',
'<tbody>',
'<tr><td colspan="3"><h4 style="font-size:20px;color:#009688;text-align:center">Thank you Student Name,</h4></td></tr>',
'<tr><td colspan="3">Your order for receipt no: <b>'+receipt_no+'</b> has the following items.</td></tr>',
'<tr><td td colspan="3"></td></tr>',
'<tr><td>#</td><td style="text-align:left">Item</td><td>Price</td></tr>',
//I want to use a for loop inside here
'<tr><td>'+foo[x].foodCount+'</td><td style="text-align:left">'+foo[x].foodName+'</td><td>'+foo[x].price+'</td></tr>',
'<tr style="font-weight:bold"><td colspan="2" style="text-align:left">Total</td><td>'+foo[0].price*foo[0].foodCount+'</td></tr>',
'</tbody>',
'</table>',
'<a class="btn btn-xs btn-info" href="javascript:void(processPrint());">Print</a>'
);
}
I am having trouble adding the for loop inside of the append method to ensure that only contents of <tr><td>'+foo[x].foodCount+'</td><td style="text-align:left">'+foo[x].foodName+'</td><td>'+foo[x].price+'</td></tr>', are changed. Any help will be appreciated.
you can't put a loop in there, you'll need to rethink how you do that - e.g. create a string with the "dynamic" content using a loop, then use that string as part of the appended content, something like
var dynamic = "";
for (var x = 0; x < foo.length; x++) { //Move the for loop from here
dynamic += '<tr><td>' + foo[x].foodCount + '</td><td style="text-align:left">' + foo[x].foodName + '</td><td>' + foo[x].price + '</td></tr>';
};
$("div#show_details").append('<table class="' + receipt_no + '" id="print_me" style="background:#ffffff;width:800px;font-family:Roboto;text-align:center;">',
'<tbody>',
'<tr><td colspan="3"><h4 style="font-size:20px;color:#009688;text-align:center">Thank you Student Name,</h4></td></tr>',
'<tr><td colspan="3">Your order for receipt no: <b>' + receipt_no + '</b> has the following items.</td></tr>',
'<tr><td td colspan="3"></td></tr>',
'<tr><td>#</td><td style="text-align:left">Item</td><td>Price</td></tr>',
dynamic,
'<tr style="font-weight:bold"><td colspan="2" style="text-align:left">Total</td><td>' + foo[0].price * foo[0].foodCount + '</td></tr>',
'</tbody>',
'</table>',
'<a class="btn btn-xs btn-info" href="javascript:void(processPrint());">Print</a>'
);
I think looping inside your jQuery append method can be more confusing but you can append a looped table columns using PHP and append it using ajax. Here's what I did just right now.
PHP query file container.php
<?php require 'dbcon.php';
$pafcmcnres = "";
$pafmcnquery = "SELECT iqa_doctypes_short FROM iqa_doctypes;";
$pafmcnexec = mysqli_query($con, $pafmcnquery);
$pafmcncnt = mysqli_num_rows($pafmcnexec);
while($pafmcnrows = mysqli_fetch_array($pafmcnexec)){
$pafcmcnres = $pafcmcnres."<td style='min-width: 45px; max-width: 45px;'></td>";
}
echo $pafcmcnres;
and for the jQuery ajax
$('#addrow_btn').click(function(){
pafmcn_rownun += 1;
$.ajax({
type: 'POST',
url: 'php/container.php',
cache: false,
success: function(pafmcn_cols){
$('#id_of_the_column_to_be_appended').append("\
<tr>\n\
<td>"+ pafmcn_rownun +"</td>\n\
<td> </td>\n\
<td> </td>\n\
<td> </td>\n\
<td> </td>"
+ pafmcn_cols +
"<td> </td>\n\
<td> </td>\n\
<td> </td>\n\
</tr>");
}
});
});
PS: the pafmcn_rownun is already declared and initialized with the value of 1 in my javacript file and each click of the button will add 1 count on the first column of the row.

Categories