JQuery append many many elements is made in one shot - javascript

I'm using jquery to append rows in a table.
I'm appending rows in an angular.forEach function in each loop but rows are rendered in my html page ine one shot : I mean the 1340 rows are displayed simultaneously insted of row by row.
I can not understand.
Here is an example of my code
angular.forEach(scope.contents, function(pack, indexPack) {
var bodyTag = '<tbody>';
if (pack.products.length > 0) {
angular.forEach(pack.products, function(product, indexProduct) {
bodyTag += '<tr>';
angular.forEach(scope.headers, function(header, indexHeader) {
var cellTag = '<td>';
var cellClass= '';
var cellContent = 'content 1';
cellTag += cellContent+'</td>';
bodyTag += cellTag;
});
bodyTag += '</tr>';
});
} else {
bodyTag += '<tr>';
angular.forEach(scope.headers, function(header, indexHeader) {
var cellTag = '<td>';
var cellClass= '';
var cellContent = 'content 2';
cellTag += cellContent+'</td>';
bodyTag += cellTag;
});
bodyTag += '</tr>';
}
bodyTag += '</tbody>';
$('#myTable').append(bodyTag);
});
Thanks for your help.

Related

Clickable table

I created a simple function in JS that generates a table. Now I want to do this: when I click on some cell of the table, the page will alert the value what is inside the cell: variable b, as you can see in the code. I tried it, but I didn´t managed it. is inside the code. I also used Jquery.
The code: JS
function gen() {
var rowData = '';
for (var a = 0; a < 5; a++) {
rowData += '<tr>';
for (var i = 0; i < 3; i++) {
rowData += '<td>';
rowData += b;
rowData += '</td>';
b++;
}
rowData += "</tr>";
}
$('#myTableId2').append(rowData);
}
HTML:
<table id="myTableId2"> </table>
<button onclick="gen()">Generate</button>
rowData += '<td onclick="alert(this.innerHTML)">';
I see you're using jQuery. You can attach a click() event to each <td> element as I do below.
Note that since b is undefined in your example, I took the liberty of giving it a random value for illustrative purposes.
function gen() {
let b = Math.floor(Math.random() * 1000) + 1; //generate random value
var rowData = '';
for (var a = 0; a < 5; a++) {
rowData += '<tr>';
for (var i = 0; i < 3; i++) {
rowData += '<td>';
rowData += b;
rowData += '</td>';
b++;
}
rowData += "</tr>";
}
$('#myTableId2').append(rowData);
//attach the click event using jQuery
$("td").click(function(){alert(this.innerText)});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="myTableId2"> </table>
<button onclick="gen()">Generate</button>

How to convert multiple CSV file to Multiple HTML table using AJAX and Javascript

I have a code which will show an HTML table generated from a csv file on button click . but i want multiple csv file to convert to multiple HTML table on a single button click . Is it possible ?
So here is my script .
$(document).ready(function(){
$('#Load-Data').click(function(){
$.ajax({
url:"OutputNew.csv",
dataType:"text",
success:function(data){
var employee_data = data.split(/\r?\n|\r/);
var table_data = '<div class="dropdown"><button class="dropbtn">Download</button><div class="dropdown-content">Download PDFDownload HTMLDownload Excel</div></div><input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for names.."><div id="VMTable"><div id="content"><table id="myTable" class="table table-striped""><thead>';
for(var count = 0; count<employee_data.length; count++) {
var cell_data = employee_data[count].split(',');
table_data += '<tr>';
for(var cell_count=0; cell_count<cell_data.length; cell_count++){
if(count === 0){
table_data += '<th id="headers" style="position=sticky">'+cell_data[cell_count]+'</th>';
}else{
if(cell_data[cell_count] .includes("Not Matching")){
var ret = cell_data[cell_count].replace('Not Matching','');
if (ret == ""){
table_data += '<td>'+ret+'</td>'
}else{
table_data += '<td data-color="green"><span>'+ret+'</span></td>';
}
}else if(cell_data[cell_count] .includes("Matching")){
var ret = cell_data[cell_count].replace('Matching','');
if (ret == ""){
table_data += '<td>'+ret+'</td>';
}else if(ret == " "){
table_data += '<td>'+ret+'</td>';
}else{
table_data += '<td data-color="green"><span class="badge-complete" style="color:Green">'+ret+'</span></td>';
}
}else{
table_data += '<td>'+cell_data[cell_count]+'</td>';
}
}
}
table_data += '</tr>';
}
table_data += '</table></div><iframe id="txtArea1" style="display:none"></iframe>';
$('#employee_table').html(table_data);
}
});
});
});
and here is HTML button
<button type="button" name="Load-Data" id="Load-Data" class="btn btn-info">Generate Report</button>
Check out this snippet:
<!DOCTYPE html>
<html>
<head>
<title>CSV Files to HTML Tables</title>
<!-- JQuery -->
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
//add your files to csv_files array
var csv_files=['username.csv', 'username-password-recovery-code.csv']
$(document).ready(function(){
$('#btn_load').click(function(){
for(var i=0; i<csv_files.length; i++)
$.ajax({
url: csv_files[i],
dataType:'text',
success:function(data){
var rows = data.split(/\r?\n|\r/);
var table = '<table border="1">';
//row - iteration
//print table header
var headings = rows[0].split(";")
table += '<thead><tr>';
for(var j=0; j<headings.length; j++)
table += '<th>' + headings[j] + '</th>';
table += '</tr></thead>';
//print table body
table += '<tbody>';
for(var j=1; j<rows.length; j++){
var data_cell = rows[j].split(";")
table += '<tr>';
for(var k=0; k<headings.length; k++)
table += '<td>' + data_cell[k] + '</td>';
table += '</tr>';
}
table += '</tbody>';
//closing table, add line break, appending result to div
table += '</table><br>';
$('#div_results').append(table);
}
});
});
});
</script>
</head>
<body>
<div id="div_results" style="border: 5px outset grey; padding: 10px;">
<h2>--- Results ---</h2>
</div>
<button id="btn_load">Get External Content</button>
</body>
</html>
Because you haven't answered my questions I am presenting you a generalized solution. You can use this code to genereate HTML Tables for any no of CSVs having any no. of columns and rows. I have added <thead> and <tbody> tags for your ease. If you not wana use than you can remove them and do any further style specific alterations.

using jquery to append rows from sql, resulting all rows appended in thead first td

I was going to use jquery to append rows from sql, but resulting all rows appended in thead first td.
enter image description here
and the code is
<body>
<table id="table">
<thead><td>A</td><td>B</td><td>C</td><td>D</td><td>E</td><td>F</td><td>G</td></thead>
</table>
</body>
</html>
<script>
$(document).ready(function(){
var sql = "select*from test";
$.ajax({
url:"query.php",
data:{
sqls:sql
},
async:false,
success:function(data){
var returned_data = JSON.parse(data);
for(var i=0;i<returned_data.length;i++){
var temp_str = "<tr class='row'>";
temp_str += "<td class='cell'>";
temp_str += "<input class='cell_vale' type='text' value='";
temp_str += returned_data[i]['firstcell']+"'>";
temp_str += "</td>";
... the other 5 cells is same ...
temp_str += "</tr>";
$("table").append(temp_str);
}
}
});
});
</script>
I tried to use tbody but failed,
also tried to remove thead,
but after it the table width will not suit to the cells,
if there are many cells in a row, the cells may display in 2 rows but one tr.
Can anyone help me?Thanks
First of all, I would suggest going over the modern approach of data binding for much easier and cleaner implementations of what you're trying to do. Have a look at VueJS or React, they will certainly help you big time!
Secondly, try moving your temp_str and row appendage outside of the for..loop, like so
var returned_data = [
{ firstcell: 'cell1' },
{ firstcell: 'cell2' },
{ firstcell: 'cell3' }
];
var temp_str = "";
for(var i = 0; i < returned_data.length; i++) {
temp_str += "<tr class='row'>";
temp_str += "<td class='cell'>";
temp_str += "<input class='cell_vale' type='text' value='";
temp_str += returned_data[i]['firstcell'] + "'>";
temp_str += "</td>";
temp_str += "</tr>";
}
$("table").append(temp_str);
And see if it works for you?

Backbone.js - Solving method

BACKBONE and Jquery
I have a piece of code:
var ChatMessage = Backbone.View.extend({
el : '#friend-list',
events : {},
initialize : function() {},
loadMessage : function(parent_id) {
//ukrycie komunikatów etc.
$("#chat_body").html('');
$("#end-record-info").hide();
$("#end-record-load").hide();
page = 1;
this.ajax(parent_id,page); //initial data load
},
ajax : function(parent_id,page) {
$.getJSON( "/**/**/"+parent_id+"/"+page, function( json ) {
$("#end-record-load").hide();
this.build(json.message, page);
page ++; //page increment
loading = false; //set loading flag off
end_record = false;
if(json.max < page){ //no more records
end_record = true; //set end record flag on
return; //exit
}
});
},
build : function(arr, page) {
alert('dgd');
html = '';
var height = 0;
arr.reverse();
$.each(arr, function(i, data){
html += '<div class="answer '+data.side+'">';
html += '<div class="avatar">';
html += '<a href="**" target="_blank">';
html += ''+data.id+'';
html += '</a>';
html += '<div class="status offline"></div>';
html += '</div>';
html += '<div class="name">';
html += '<a href="**" target="_blank">';
html += data.username;
html += '</a>';
html += '</div>';
html += '<div class="text">';
html += data.content;
html += '</div>';
html += '<div class="time">';
if (data.side != 'left') {
html += data.dateSendMessage
}
else {
if (data.read == 0) {
html += 'xxx';
}
else {
html += 'xxx';
}
}
html += '</div>';
html += '</div>';
});
var nh = $('#chat_body').html();
$('#chat_body').html(html+nh);
if (page == 1) {
$('#chat_body .answer').each(function(i, value){
height += parseInt($(this).height());
});
height += '';
$('.chat2').scrollTop(height);
}
}
});
In AJAX method I want to build method
this.build(json.message, page);
But something does not work and I get an error.
pm2.js:67TypeError: this.build is not a function. (In 'this.build(json.message, page)', 'this.build' is undefined)
Can anyone help? What changes in this piece of code can be by the way?
Piotr
You should probably save current context before calling getJSON:
ajax : function(parent_id,page) {
var self = this;
$.getJSON( "/**/**/"+parent_id+"/"+page, function( json ) {
...
self.build(json.message, page);

How to add image in table cell

Hi I want to add image in table cell according to condition in table. I am using dynamic table as follow:
$.get('http://myDomain.com/RIA/topIndiaDetails.asp', function(data)
{
console.log("####"+data);
var up = new Image();
var down = new Image();
up.src = "../../jquery.mobile/images/up.png";
down.src = "../../jquery.mobile/images/down.png"
substr = data.split('$');
//alert(substr.length);
//var theader = '<table border="1">\n';
//<table id="auditOverview" border="1">
var theader = '<table border="1" id=\"tableId\">\n';
var tbody = '';
for (var out = 1;out<substr.length-1;out++)
{
//alert(substr[out]);
tbody += '<tr>';
var pra = substr[out].split('|^');
//alert('pra.length is: '+pra.length);
for (var i=0;i<pra.length-1;i++)
{
tbody += '<td>';
if (pra[i]=="Red")
{
pra[i].append("<img id='theImg' src='../../jquery.mobile/images/down.png'/>");
}
else if (pra[i]=="Green")
{
pra[i].append("<img id='theImg' src='../../jquery.mobile/images/up.png'/>");
}
tbody += pra[i];
tbody += '</td>'
}
tbody += '</tr>\n';
}
var tfooter = '</table>';
document.getElementById('wrapper').innerHTML = theader + tbody + tfooter;
});
Now I am checking condition as if (pra[i]=="Green") then I want to add image in cell insted of "Green" string and same for Red string. Any help will be appreciated. Thanks in advance.
instead of :
pra[i].append("<img id='theImg' src='../../jquery.mobile/images/up.png'/>");
do
pra[i] = "<img id='theImg' src='../../jquery.mobile/images/up.png'/>";

Categories

Resources