Create a TBODY using Array - javascript

I have an array that looks like this.
now here is my code for that
success: function(data) {
data = $.parseJSON(data);
for (i = 0; i < data.length; i++) {
console.log(data[i]);
}
}
the console.log displays it
here is my table
<table id "tblreport" class="mytable" style="width: 900px; margin-right: auto; height: 18px;" border="1">
<thead>
//Table Headers here
</thead>
<tbody id = "body">
</tbody>
</table>
my question is using that array how can I make it as a data in tbody?

This code should be working for you.. Put this in your success callback.
demo
var data = [['a','b','c'],['a','b','c'],['a','b','c'],['a','b','c'],['a','b','c']];
var tb = $("#body");
for(i = 0; i < data.length; i++){
var tr = $("<tr />");
for(var x in data[i]){
var td = $("<td />");
td.html(data[i][x]);
tr.append(td);
}
tb.append(tr);
}

Pretty sure you want this:
for(var i=0,a,tr,l=data.length; i<l; i++){
a = data[i]; tr = document.createElement('tr');
for(var n=0,td,c=a.length; n<c; n++){
td = document.createElement('td'); td.innerHTML = a[n]; tr.appendChild(td);
}
$('#body').append(tr);
}

var tbodyHtml = "";
$.each(data, function( index, value ) {
tbodyHtml += "<tr>";
$.each(value, function( i, v ) {
tbodyHtml += "<td>"+v+"<\td>";
});
tbodyHtml += "</tr>";
});
$("#body").html(tbodyHtml);

success: function(data) {
data = $.parseJSON(data);
//variable to hold all incoming data
var htmlData = ''
for (i = 0; i < data.length; i++) {
console.log(data[i]);
$("#body").append('<tr><td>' + data[i] + '</td><tr>');
}
}
let me know if this works.

Related

javascript function not working (TableFilter library)

I'm trying to make a table in my web app filterable. The TableFilter library seems to be really good but I'm not able to make it work (only in the web app since it works with a simple html page).
this is the code of my page:
<html>
<head>
<title>Show Elements In Table Page</title>
<script src="~/tableFilter/tablefilter.js"></script>
<script src="~/tableFilter/tablefilter_all.js"></script>
<script src="~/tableFilter/tablefilter_all_min.js"></script>
<script src="~/tableFilter/tablefilter_min.js"></script>
</head>
<body id="pageBody" onload="createTable(getLocalItem('selectedTable'), 'elementsTable');
hideElement('loading');
document.getElementById('tableName').innerHTML = getLocalItem('selectedTable');
prova();">
<h3 id="loading">loading...</h3>
<div style="margin-left: 1em; margin-top: 1em;">
<h3 id="tableName"></h3>
<table align="left" border="1" cellpadding="5" cellspacing="0" id="elementsTable">
<!--the table loads with the createTable() function-->
</table>
</div>
<script language="javascript" type="text/javascript">
setFilterGrid("elementsTable");
<!--this is not working-->
</script>
</body>
</html>
this is the createTable() js function:
function createTable(tableName, tableId) {
fetch(domain + urlParameters + tableName)
.then(r => r.text())
.then(j => JSON.parse(j))
.then(o => {
var cols = getVarNames(o);
//header
var tableHtml = "<thead><tr>";
for (var i = 0; i < cols.length; i++) {
tableHtml += "<th>" + cols[i] + "</th>";
}
tableHtml += "</tr></thead>";
//body
tableHtml += "<tbody><tr>";
for (var i = 0; i < o.length; i++) {
for (var j = 0; j < cols.length; j++) {
tableHtml += "<td>" + o[i][cols[j]] + "</td>";
}
tableHtml += "</tr>";
}
tableHtml += "</tbody>";
//insertion in document
document.getElementById(tableId).innerHTML = tableHtml;
});
}
function getVarNames(list) {
var columns = [];
for (var i = 0; i < list.length; i++) {
var row = list[i];
for (var k in row) {
if ($.inArray(k, columns) == -1) {
columns.push(k);
}
}
}
return columns;
}
the table is loaded but it is not filterable. the script in the body seems to not recognize the table. how could i solve?
i solved creating my own query methods in javascript. maybe this could be helpful for someone.
var tableObject; //variable storing the json object form the api
function createTable(tableName, tableId) {
fetch(domain + urlParameters + tableName)
.then(r => r.text())
.then(j => JSON.parse(j))
.then(o => {
tableObject = o;
//insert filtering variables
var cols = getVarNames(tableObject);
//header
var tableHtml = "<thead><tr>";
for (var i = 0; i < cols.length; i++) {
tableHtml += "<th>" + cols[i] + "</th>";
}
//insert selection and filtering tools
tableHtml += "<tr>";
for (var i = 0; i < cols.length; i++) {
tableHtml += "<td><textarea class=\"filter\" rows=\"1\" placeholder=\"input\" style=\"resize: none;\"></textarea></td>";
//add some kind of tag matching the column -> maybe a class? or an id?
}
tableHtml += "</tr>";
tableHtml += "</tr></thead>";
//body
tableHtml += "<tbody id=\"tableBody\"><tr>";
for (var i = 0; i < tableObject.length; i++) {
if (objectIncludesFilters(tableObject[i], cols, getValuesFilters())) {
for (var j = 0; j < cols.length; j++) {
tableHtml += "<td>" + tableObject[i][cols[j]] + "</td>";
}
tableHtml += "</tr>";
}
}
tableHtml += "</tbody>";
//insertion in document
document.getElementById(tableId).innerHTML = tableHtml;
});
}
function getVarNames(list) {
var columns = [];
for (var i = 0; i < list.length; i++) {
var row = list[i];
for (var k in row) {
if ($.inArray(k, columns) == -1) {
columns.push(k);
}
}
}
return columns;
}
function getValuesFilters() {
const collection = document.getElementsByClassName("filter");
var values = [];
for (var i = 0; i < collection.length; i++) {
var value = collection[i].value;
values.push(value);
if (value == null) {
values.push("");
}
}
return values;
}
function objectIncludesFilters(obj, cols, filters) {
var result = true;
for (var i = 0; i < filters.length; i++) {
if (!obj[cols[i]].toLowerCase().includes(filters[i].toLowerCase())) {
result = false;
}
}
return result;
}

Grabbing elementID

I am creating a table with td ids as follows(id=concatenate(row,column)):
function createTable() {
document.body.innerHTML += '<table border="1" id="mytable"></table>';
for (var i = 0; i < 4; i++) {
document.getElementById("mytable").innerHTML += '<table border="1"><tr id="row' + i + '"></tr></table>';
for (var k = 0; k < 4; k++) {
document.getElementById("row" + i).innerHTML += '<td id=' + i + k + '></td>';
}
}
}
Then I want to change the background color of each cell depending on whether its value is >5 or below. This is the onclick function I call for each cell:
function clickable() {
var table = document.getElementById("mytable");
if (table != null) {
for (var i = 0; i < table.rows.length; i++) {
for (var j = 0; j < table.rows[i].cells.length; j++)
table.rows[i].cells[j].onclick = function () { colorChange(i, j); };
}
}
}
function colorChange(i, j) {
if (document.getElementById("" + i + j).innerHTML > 5) {
document.getElementById("" + i + j).style.backgroundColor = "green";
}
}
but the debugger catches a typeError for trying to access a property of null in the first line of colorChange, which means my method of getting the elementID is wrong. What's the correct way to get the element ID?
It's because you're using vars for loop variables you always have i=4 and j=4 on click. Just replace those with let:
function clickable() {
var table = document.getElementById("mytable");
if (table != null) {
for (let i = 0; i < table.rows.length; i++) {
for (let j = 0; j < table.rows[i].cells.length; j++)
table.rows[i].cells[j].onclick = function () { colorChange(i, j); };
}
}
}
You don't need any of the i and j business. Just select the cell elements directly and loop through them to add an event listener, using querySelectorAll, as per the demo below.
N.B. You mentioned that you want to "change the background color of each cell depending on whether its value is >5 or below" ...but how are you defining the "value"? It's isn't clear. In the colorChange function, you try to test the value using the cell's "innerHTML", but your cells don't have any content anyway, so it would never work.
Therefore, for the purposes of the demo, I've assumed you intended to populate the cells with the values of i and k, and then interpret those as a single number when you do the test in colorChange.
Also <table border="1"> needed to be removed. You can't have a table directly within another table. And it's not necessary, anyway.
function createTable() {
document.body.innerHTML += '<table border="1" id="mytable"></table>';
for (var i = 0; i < 4; i++) {
document.getElementById("mytable").innerHTML += '<tr id="row' + i + '"></tr></table>';
for (var k = 0; k < 4; k++) {
document.getElementById("row" + i).innerHTML += '<td id=' + i + k + '>' + i + k + '</td>';
}
}
}
function clickable() {
var cells = document.querySelectorAll("#mytable td");
cells.forEach(function(cell) {
cell.addEventListener("click", colorChange);
});
}
function colorChange() {
console.log(this.innerHTML);
if (this.innerHTML > 5) {
this.style.backgroundColor = "green";
}
}
createTable();
clickable();
See https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll for documentation.
I think you're missing an opening curly bracket on the "j" loop of clickable
for (var j = 0; j < table.rows[i].cells.length; j++)
I also changed colorChange() to work with the event target:
function createTable() {
document.body.innerHTML += '<table border="1" id="mytable"></table>';
for (var i = 0; i < 4; i++) {
document.getElementById("mytable").innerHTML += '<table border="1"><tr id="row' + i + '"></tr></table>';
for (var k = 0; k < 4; k++) {
document.getElementById("row" + i).innerHTML += "<td id=" + i + k + ">" + Math.floor(Math.random() * 10) + "</td>";
}
}
}
function clickable() {
var table = document.getElementById("mytable");
if (table != null) {
for (var i = 0; i < table.rows.length; i++) {
for (var j = 0; j < table.rows[i].cells.length; j++) {
table.rows[i].cells[j].onclick = function(event) {
colorChange(event);
};
}
}
}
}
function colorChange(event) {
const cell = event.target;
if (cell.innerHTML > 5) {
cell.style.backgroundColor = "green";
}
}
<button onclick="createTable();clickable()">run</button>

Table Issue in WYSIWYG Editor

I'm creating an HTML WYSIWYG editor from scratch and I have an issue when it comes to tables. Somehow, I'm able to create the pretended number of columns but only one row (without the heading). I'd be thankful if anyone could tell what's the issue.
HTML
<!DOCTYPE html>
<html>
<head>
<title>Text Editor</title>
</head>
<body>
<div id="Ribbon">
<div id="Ribbon-3">
<button class="RibbonBtn" id="TableButton" title="Insert Table"><i class="fas fa-table"></i></button>
</div>
</div>
<div id="TextArea">
<div id="WYSIWYG" contenteditable="true"></div>
</div>
</div>
</body>
</html>
JS
window.addEventListener("load",function(){
$('#TableButton').click(function(){
var colnum = prompt("Indicate the number of columns");
var rownum = prompt("Indicate the number of rows");
var table = "";
var tablehead = "";
var tablebodytext = "";
for (var i = 0; i < colnum; i++) {
tablehead += "<th>null</th>";
}
var tablebody = [];
for (var i = 0; i < rownum; i++) {
var tablebodyrow = "";
for (var i = 0; i < colnum; i++) {
tablebodyrow += "<td>null</td>";
}
tablebody += "<tr>" + tablebodyrow + "</tr>";
}
table = "<table><tr>" + tablehead + "</tr>" + tablebody+ "</table>";
document.execCommand("insertHTML",false, table);
});
},false);
I chose 5 columns and 4 rows, but instead it created 5 columns and only 1 row
I've found the error. Such a dumb mistake...
I was using the same "i" var for the nested for loop and its parent loop.
This is the right version:
$('#TableButton').click(function(){
var colnum = prompt("Indicate the number of columns:");
var rownum = prompt("Indicate the number of rows:");
var table = "";
var tablehead = "";
var tablebodytext = "";
for (var i = 0; i < colnum; i++) {
tablehead += "<th>null</th>";
}
var tablebody = [];
for (var i = 0; i < rownum; i++) {
var tablebodyrow = "";
for (var i1 = 0; i1 < colnum; i1++) {
tablebodyrow += "<td>null</td>";
}
tablebody += "<tr>" + tablebodyrow + "</tr>";
}
table = "<table><tr>" + tablehead + "</tr>" + "<tbody>" + tablebody + "</tbody>" + "</table>";
document.execCommand("insertHTML",false, table);
});

Converting CSV input in textarea to dynamic table

This picture defines what I need
I want that the data I enter dynamically to be converted to table with each comma defining the column and the newline defining the new row.
Below is the code I have tried. Can I have a better approach to this problem?
<script>
function myFunction()
{
var x = document.getElementById("textarea").value.split(" ");
var customers = new Array();
customers.push(x[0]);
customers.push(x[1]);
customers.push(x[2]);
var table = document.createElement("TABLE");
table.border = "1";
//Get the count of columns.
var columnCount = customers[0].length;
//Add the header row.
var row = table.insertRow(-1);
for (var i = 0; i < columnCount; i++) {
var headerCell = document.createElement("TH");
headerCell.innerHTML = customers[0][i];
row.appendChild(headerCell);
}
//Add the data rows.
for (var i = 1; i < customers.length; i++) {
row = table.insertRow(-1);
for (var j = 0; j < columnCount; j++) {
var cell = row.insertCell(-1);
cell.innerHTML = customers[i][j];
}
}
var dvTable = document.getElementById("dvTable");
dvTable.innerHTML = "";
dvTable.appendChild(table);
}
</script>
<html>
<head>
<title>Player Details</title>
</head>
<body align = "center">
<h3 align = "center"><b>Input CSV</b></h3>
<p align = "center"><textarea rows="10" cols="50" name = "csv" id = "textarea"></textarea></p><br>
<button type="button" id = "convert" onclick="myFunction()">Convert</button><br>
<br>
<div id = "team"></div>
</body>
</html>
You need to split the data first using newline (\n) and then using comma (,) character.
The table can be created as string and finally inserted to the correct div.
Refer the code below to get you started.
function myFunction() {
var tbl = "<table class='table table-responsive table-bordered table-striped'><tbody>"
var lines = document.getElementById("textarea").value.split("\n");
for (var i = 0; i < lines.length; i++) {
tbl = tbl + "<tr>"
var items = lines[i].split(",");
for (var j = 0; j < items.length; j++) {
tbl = tbl + "<td>" + items[j] + "</td>";
}
tbl = tbl + "</tr>";
}
tbl = tbl + "</tbody></table>";
var divTable = document.getElementById('team');
console.log(tbl);
divTable.innerHTML = tbl;
}
I've used bootstrap for css, you may want to use your own (or not).
Refer jsFiddle here.

Assign Id and iterate through rows in Javascript

I created a table, which seems to work fine, but I have problems assigning an id to this table, count how many rows it has, and assign each row an id. The debugger says:
TypeError: document.getElementById(...) is null
I couldn't figure out what I did wrong. Can someone please help? I commented my questions in the code below as well:
function populateTable(list){
var tableContent = "<table>";
for (var i = 0; i < list.length; ++i) {
var record = list[i];
tableContent += "<tr><td>" + record.Title + "</td></tr>\n";
}
tableContent += "</table>";
tableContent.id="orders";
var rows = document.getElementById("orders").rows.length;//why is this null?
document.getElementById("test").innerHTML = rows;
for (var i=0; i< rows; ++i){
//how do I assign an id for the element here?
}
}
You can do this in this way:
HTML:
<div id="here"> </div> <!-- the table will be added in this div -->
JavaScript:
function populateTable(list){
var tableContent = document.createElement('table');
for (var i = 0; i < list.length; ++i) {
var record = list[i];
var cell = document.createElement('td');
var row = document.createElement('tr');
var textnode = document.createTextNode(record.Title);
cell.appendChild(textnode);
row.appendChild(cell);
tableContent.appendChild(row);
}
tableContent.id="orders";
document.getElementById("here").appendChild(tableContent); // the table is added to the HTML div element
var rows = document.getElementById("orders").rows;
for (var i=0; i < rows.length; ++i){
rows[i].id = "myId" + (i+1); // this is how you assign IDs
console.log(rows[i]);
}
}
var persons = [{Title:"John"}, {Title:"Marry"}];
populateTable(persons);
Edit
It seems you don't know how to properly create a DOM from javascript:
http://www.w3schools.com/jsref/met_document_createelement.asp
Old answer
This line:
var rows = document.getElementById("orders").rows.length;//why is this null?
Get elements from HTML document by id. And it looks like you have not added tableContent yet to the document.
Here's my suggestion (read the comments in the code):
// This will create a table element and return it
function createTable(list){
var table = document.createElement('table'); // This is an actual html element
table.id = 'orders'; // Since it's an html element, we can assign an id to it
tableHtml = ''; // This empty string will hold the inner html of the table we just created
for (var i = 0; i < list.length; ++i) {
var record = list[i];
// we can assign the id here instead of looping through the rows again
tableHtml += '<tr id="row-' + i + '"><td>' + record.Title + '</td></tr>';
}
table.innerHTML = tableHtml; // We insert the html into the table element and parse it
var rows = table.rows.length; // We already have a reference to the table, so no need of getElementById
alert('rows'); // rows holds the number of rows. You can do whatever you want with this var.
return table; // return the table. We still need to insert it into the dom
}
// Create a new table and hold it in memory
var myTable = createTable([{Title:'One'}, {Title:'Two'}, {Title:'Three'}]);
// Inset the newly created table into the DOM
document.getElementById('parent-of-table').appendChild(myTable);
Hope this helps
This is already been answered, but here's my version without all the comments:
function createTable(list){
var table = document.createElement('table');
table.id = 'orders';
tableHtml = '';
for (var i = 0; i < list.length; ++i) {
tableHtml += '<tr id="row-' + i + '"><td>' + list[i].Title + '</td></tr>';
}
table.innerHTML = tableHtml;
var rows = table.rows.length;
alert('rows');
return table;
}

Categories

Resources