td's in table creating with jquery without html - javascript

Here is my jsfiddle work. I have some issues with generating table without any html. I have one json object that i need to itterate and to put keys and values in table like:
<tr> <td> key </td> <td> key </td> ... </tr>
<tr> <td> val </td> <td> val </td> ... </tr>
I tried first to generate the table like this one, but next i wanted to use jquery version of creating td's and tr's, but the all keys and values were appended in only one td and actually this is not what i want.

You have to loop through keys the first time to set the head of table, after that make the rows inside each and append every one to the table to make the body of your table, check example code bellow :
$.ajax({
type : "POST",
dataType : "json",
url : '/echo/json/',
data : { json: JSON.stringify( jsonData ) },
success : function(data){
var jsn = $(data.markers);
//First time append table head
if(!header)
{
var row = $('<tr></tr>');
for(key in jsn[0])
{
row.append('<th>'+key+'</th>');
}
table.append(row);
header = true;
}
for ( var i = 0; i < jsn.length ; i++){
var row = $('<tr></tr>');
$.each(jsn[i], function(key,val)
{
row.append('<td>'+val+'</td>');
});
table.append(row);
}
}
});
Take a look at Working fiddle.
Hope this helps.

The issue was in the scope of the col and row variables. You must reassign them in the loop, or redeclare.
Here is the updated jsfiddle. By the way there is no need to use for loop. In jQuery it is enough to use the $.each function on the object.
From here you can see how to create table structure and replace the key and val with the actual data you need.

You need to create new row object in each for iteration:
for (var mrksIndex = 0, mrksLength = jsn.length; mrksIndex <= mrksLength; ++mrksIndex) {
row = $("<tr/>");
$.each(jsn[mrksIndex], function (key, val) {
col = $("<td/>");
col.append(key);
row.append(col);
table.append(row);
});
}
Demo: https://jsfiddle.net/6dw2u8uz/15/

Related

How to add condition and change the color of table row

I have a javascript which will read the value from the JSON and creates a table dynamically in the HTML page.
<div style="width:700px;padding:20px;S">
<h1 style="text-align:center"><i style="color:#ccc">ALM Server Availability</i></h1>
<table id="records_table" class="table">
<tr>
<th>Server Name</th>
<th>Availability %</th>
</tr>
</table>
</div>
JQUERY :
function availshow(series) {
// 1. remove all existing rows
$("tr:has(td)").remove();
$.each(series.data.hostgroup.hosts, function (index, test) {
$('<tr>').append(
$('<td>').text(test.name),
$('<td>').text(parseInt((test.time_up/86400)*100)),
).appendTo('#records_table');
});
}
Now i need to check the condition if value of (test.time_up/86400)*100) < 100 , then i need to make that particular row into red color. How can I achieve it.
You can do this, looping through each tr then looking for 2nd td value
$('#records_table tr').each(function() {
var $td = $(this).find('td:eq(1)');
var value = $td.text();
if (parseInt(value) < 100) {
$td.css('background-color', 'red');
}
});
Your JQuery fucntion should be something like this:
var i=0
function availshow(series) {
// 1. remove all existing rows
$("tr:has(td)").remove();
$.each(series.data.hostgroup.hosts, function (index, test) {
i=(test.time_up/86400)*100);
$("<tr"+(i < 100 ? "class:'redBlock'": "")+">").append(
$('<td>').text(test.name),
$('<td>').text(parseInt((test.time_up/86400)*100)),
).appendTo('#records_table');
});
}
And then create that said class in .css file with all the style you want:
.redBlock{
background-color:red;
}
Hope I could help.
Happy Coding :)

Dynamically add values from a csv in an html table using javascript/jquery

I have a dynamically generated CSV file from another vendor that I am puling in and need to show in a table on my site. The problem is I need to be able to manipulate the data from the CSV so it can show the corrected values in the html table. In the end I need the HTML table to just display the Products, not the Mixed Sets.
I am using jquery and the papaparse library to get the data and parse it in a table in html. My codepen is here:
https://codepen.io/BIGREDBOOTS/pen/YQojww
The javascript pulls the initial csv values and display in a table, but I can't figure out how to to add together the values. If there is a better way of going about this, like converting the CSV to some other form of data like JSON, That is fine too.
My CSV looks like this:
product_title,product_sku,net_quantity
Product 1,PRD1,10
Product 2,PRD2,20
Product 3,PRD3,30
Mixed Set 1,MIX1,100
Mixed Set 2,MIX2,50
Mixed Set 3,MIX3,75
The Javascript I am using is:
function arrayToTable(tableData) {
var table = $('<table></table>');
$(tableData).each(function (i, rowData) {
var row = $('<tr class="rownum-' + [i] + '"></tr>');
$(rowData).each(function (j, cellData) {
row.append($('<td class="' + [i] + '">'+cellData+'</td>'));
});
table.append(row);
});
return table;
}
$.ajax({
type: "GET",
url: "https://cdn.shopify.com/s/files/1/0453/8489/t/26/assets/sample.csv",
success: function (data) {
$('body').append(arrayToTable(Papa.parse(data).data));
}
});
My rules for the mixed set:
Mixed Set 1 should add 100 to Product 1 and Product 2.
Mixed Set 2 should add 50 to Product 2 and Product 3.
Mixed Set 3 should add 75 to Product 1, Product 2 and Product 3.
I'd like to end up with Just the products output, and the correct numbers added to the formula.
The end result would be a table with Product 1 = 185, Product 2 = 245, and Product 3 = 155.
While it would be even better if the top THEAD elements were in a "th", It's fine if that is too complicated.
<table>
<tbody>
<tr class="rownum-0">
<td class="0">product_title</td>
<td class="0">product_sku</td>
<td class="0">net_quantity</td>
</tr>
<tr class="rownum-1">
<td class="1">Product 1</td>
<td class="1">PRD1</td>
<td class="1">185</td>
</tr>
<tr class="rownum-2">
<td class="2">Product 2</td>
<td class="2">PRD2</td>
<td class="2">245</td>
</tr>
<tr class="rownum-3">
<td class="3">Product 3</td>
<td class="3">PRD3</td>
<td class="3">155</td>
</tr>
</tbody>
</table>
Without knowing the size of the dataset you're working with, I suggest you first iterate through all the CSV dataset in order to populate a list of products with the correct values, and then iterate again on that to populate your HTML table:
function datasetToMap(data) {
var ret = {};
//Initialize a map with all the product rows
$(data).each(function(index, row) {
if(row[0].startsWith("Product")) {
ret[row[1]] = row; //Using the SKU as the key to the map
}
});
//Apply your mixed sets rules to the elements in the ret array
$(data).each(function(index, row) {
if(row[1] === "MIX1") {
ret["PRD1"][2] += 100;
ret["PRD2"][2] += 100;
}
//Do the same for Mixed sets 2 and 3
});
return ret;
}
function appendMapToTable(map) {
var $table = $('#my-table');
Object.keys(map).forEach(function(key, i) {
var rowData = map[key];
var row = $('<tr class="rownum-' + [i] + '"></tr>');
$(rowData).each(function (j, cellData) {
row.append($('<td class="' + [j] + '">'+cellData+'</td>'));
});
$table.append(row);
});
}
$.ajax({
type: "GET",
url: "https://cdn.shopify.com/s/files/1/0453/8489/t/26/assets/sample.csv",
success: function (data) {
appendMapToTable(datasetToMap(Papa.parse(data).data));
}
});
Note that this expects a table with id my-table to be already present in your HTML: you could manually parse the first row of your CSV data to add the table headings.
Also note that if your CSV dataset is very big this is definitely not an optimal solution, since it requires iterating through all its lines twice and then iterating again through all the list built with computed values.

DataTables issue: VM9075 dataTables.min.js:24Uncaught TypeError: Cannot set property '_DT_CellIndex' of undefined

I just started using DataTables and everything works fine when creating the table.
When I display 5, 24, 47 rows in my table, DataTables behaves as I would expect.
But I have this table that has around 700 rows and I get the error in Google Chrome,
"VM9075 dataTables.min.js:24Uncaught TypeError: Cannot set property '_DT_CellIndex' of undefined "
and in IE 9,
"SCRIPT5007: Unable to set value of the property '_DT_CellIndex': object is null or undefined
jquery-1.10.2.min.js, line 4 character 2367"
I don't have jQuery included twice btw.
I'm not sure how to proceed from here.
I tried to use the unminified version of the .js file to debug it more myself but i kept getting an "ext" method or property is undefined and couldn't fix that either.
Any help is appreciated!
I figured it out
The biggest issue was not knowing exactly what this error actually meant.
In my case it meant "the number of every <td> element in your table that is a child of a <tr> element doesn't match the number of <th> elements that are a child of the <thead> element."
My table was being generated by the server, and some of the <tr> elements had 27 <td> children (which was filling the whole width of the table up, but some of the <tr> elements only had 3, 4, or 5, ... <td> child elements which isn't a valid table.
I solved it by adding empty <td> elements in my table for the <tr> elements that lacked the correct number of <td> elements
var makeTableValidObject = {
thisWasCalled: 0,
makeTableValid: function() {
var tableToWorkOn = document.getElementById("table1");
//check the number of columns in the <thead> tag
//thead //tr //th elements
var numberOfColumnsInHeadTag = tableToWorkOn.children[1].children[0].children.length;
var numberOf_trElementsToValidate = tableToWorkOn.children[2].children.length;
//now go through each <tr> in the <tbody> and see if they all match the length of the thead columns
//tbody //all trs//all tds elements
//tableToWorkOn.children[2].children.children);
for(var i = 0; i < numberOf_trElementsToValidate; i++) {
//row my row make sure the columns have the correct number of elements
var tdColumnArray = tableToWorkOn.children[2].children[i].children
var trElementToAppendToIfNeeded = tableToWorkOn.children[2].children[i];
if(tdColumnArray.length != numberOfColumnsInHeadTag) {
//since they don't match up, make them valid
if(tdColumnArray.length < numberOfColumnsInHeadTag) {
//add the necessary number of blank <td> tags to the <tr> element to make this <tr> valid
var tdColumnArrayLength = tdColumnArray.length;
for(var j = 0; j < (numberOfColumnsInHeadTag - tdColumnArrayLength); j++) {
var blank_tdElement = document.createElement("td");
blank_tdElement.id = "validating_tdId" + i + "_" + j;
trElementToAppendToIfNeeded.appendChild(blank_tdElement);
}
}
else {
//TODO: remove <td> tags to make this <tr> valid if necessary
}
}
}
}
};
Edit 1:
It has been awhile and this question is still getting a bunch of views. I have since updated the code.
I replaced the first line of code with the second line to be more general
var numberOfColumnsInHeadTag = tableToWorkOn.children[1].children[0].children.length;
var numberOfColumnsInHeadTag = tableToWorkOn.querySelectorAll('thead')[0].querySelectorAll('th');
Pretty much where ever in the prior code you see the children.children I replaced that with the querySelectorAll(...) Function.
It uses css selectors which makes it amazingly powerful.
stay blessed
Ran into this same issue and implemented this same solution (essentially) in jquery based on Coty's. Hope this helps someone. :)
$( '.table' ).each(function( i ) {
var worktable = $(this);
var num_head_columns = worktable.find('thead tr th').length;
var rows_to_validate = worktable.find('tbody tr');
rows_to_validate.each( function (i) {
var row_columns = $(this).find('td').length;
for (i = $(this).find('td').length; i < num_head_columns; i++) {
$(this).append('<td class="hidden"></td>');
}
});
});
As answered by Coty, the problem lies in the mismatch of td elements generated in the header and body of table.
I'd like to highlight one of the reasons why it can occur (For .Net Users).
If Page numbers are being displayed at the end of gridview, they can disrupt table structure.
Remove AllowPaging="true" from your gridview to solve this.
And no worries because Datatable handles Paging.
you always keep four column but sometimes you will receive or append null td or only one td, td count always match with total column so when you does not have record then make td as following.
<th>No</th>
<th>Name</th>
<th>place</th>
<th>Price</th>
----------------------------------------
<td colspan="4">Data not found.</td>
<td style="display: none;"></td>
<td style="display: none;"></td>
<td style="display: none;"></td>
this error can also be triggered if you try to set options for the responsive extension for more columns than you have.
$( '.table' ).each(function( i ) {
var worktable = $(this);
var num_head_columns = worktable.find('thead tr th').length;
var rows_to_validate = worktable.find('tbody tr');
rows_to_validate.each( function (i) {
var row_columns = $(this).find('td').length;
for (i = $(this).find('td').length; i < num_head_columns; i++) {
$(this).append('<td class="hidden"></td>');
}
});
});

making html table sortable (with headers and data loaded using javascript)

I have the following html in a website:
<table id="list" class="tablesorter">
<thead id="header">
</thead>
<tbody id="rows">
</tbody>
</table>
I load the header and rows of the table using javascript. Example of how I fill the headers:
$.get( '/getdata',{}, function(mydata) {
// Parses JSON Into Array
var array = $.parseJSON(mydata);
var html = '<tr>';
html+='<th>#</th>';
html+='<th>One</th>';
html+='<th">TOTAL</th>';
var available = {};
for (var i = 0; i < array.length; i++) {
available_item = array[i];
html+='<th><abbr title="'+array[i].text+'"><img src="img/flags2/'+array[i].country+'.png"></img></abbr></th>';
};
html += '</tr>';
$(html).appendTo('#header');
});
The rows are filled in a similar way: ajax get, for loop, and append to html.
Now I need the table columns to be sortable.
I was trying to get it work with jquery tablesorter but it is not working. I suppose that it is not working because my data is loaded using javascript.
How can I make this table sortable?
Add $("#list").tablesorter(); at the end (when table is already filled with all data, thead and tbody)... I am using the same in my application and works fine.
use below code. add $("#list").tablesorter(); at data loop end.
$.get( '/getdata',{}, function(mydata) {
// Parses JSON Into Array
var array = $.parseJSON(mydata);
var html = '<tr>';
html+='<th>#</th>';
html+='<th>One</th>';
html+='<th">TOTAL</th>';
var available = {};
for (var i = 0; i < array.length; i++) {
available_item = array[i];
html+='<th><abbr title="'+array[i].text+'"><img src="img/flags2/'+array[i].country+'.png"></img></abbr></th>';
if(array.length === (i+1)){
html += '</tr>';
$(html).appendTo('#header');
$("#list").tablesorter();
}
};
});
Yes you can do it
Looking at your title making html table sortable (with headers and data loaded using javascript)
It doest matter if you are loading data via jquery or simply using php ...
look for datatables in bootstrap .. This plugin provides all types of data manipulation with the tables that also includes sorting of the data ... you can also perform search in the table. All you have to do is give your table some id like "mytable" then write
$(document).ready( function () {
$('#mytable').DataTable();
} );
after that you can start to include different attributes to select the type of sorting searching etc ... hope that helps

JavaScript DOM not being read in html table

I produce an int from JSON data
var f_page = ["TheHouseofMarley"];
retrieveData(f_page[0]);
function retrieveData(teamName) {
var baseURL = 'http://graph.facebook.com/';
$.getJSON(baseURL+teamName+"&callback=?", function(data) {
$('#FBlikes').append(data.likes)
});
};
and this works, it gives ~ 8407
I have a chart that reads data from < table id="chartData">
Grabbing the data from the table
I use a jQuery selector — $('#chartData td') — to select all the data cells in the table. I can then iterate through these cells with the jQuery each() method. For each cell, I determine if it's a label (e.g. "SuperWidget") or a value (e.g. "FBLike") cell, based on whether it's in the left or right column. I then store the cell contents under the 'label' or 'value' key in an associative array, which we then place inside the chartData array.
$('#chartData td').each( function() {
currentCell++;
if ( currentCell % 2 != 0 ) {
currentRow++;
chartData[currentRow] = [];
chartData[currentRow]['label'] = $(this).text();
} else {
var value = parseFloat($(this).text());
totalValue += value;
value = value.toFixed(2);
chartData[currentRow]['value'] = value;
}
// Store the slice index in this cell, and attach a click handler to it
$(this).data( 'slice', currentRow );
$(this).click( handleTableClick );
The problem is when I insert this number into < table id="chartData"> it is not read by the chart!
<table id="chartData">
<tr style="color: #0DA068">
<td>Number of Likes </td><td><span id='FBlikes'></span> </td> //Not Read!
</tr>
<tr style="color: #194E9C">
<td>MegaWidget</td><td>20000</td> //This is Read by the Chart!
</tr>
In short: Javascript output is not being read from HTML table.
Could anyone point me in some direction? I'm really new at code.
Usually this problem occurs in Ajax.
Build a string appending "data.likes" to it. Then finally assign the string to the element.
This may sound absolutely stupid, but it worked for me. Whenever i use to build a table dynamically in jQuery using the ajax response string, i would never get a table. Then i followed the procedure I mentioned.
If my solution works, some one please help me understand why is it so.

Categories