Hello I try to generate an HTML Table with two arrays. Where one array is for the Headers and the other one is for the rows. The arrays work like a blast but the generation of the HTML-Table wont work.....
Here is my little Function: (For the arrays and they work like a blast)
function loadDepartments() {
var query = "$select=DepartmentID,WEBName";
getListItems("example.at", "WEBepartments", query, function (results) {
results.forEach(function (result) {
departments.push({
name: result.WEBName,
id: result.DepartmentID
});
});
loadCountries();
},
function (error) {
console.log(error);
});
}
function loadCountries() {
var query = "$select=CountryID,WEBName,Acronym";
getListItems("https://intranet.windkraft.at/", "WEBCountries", query, function (results) {
results.forEach(function (result) {
countries.push({
name: result.WEBName,
id: result.CountryID,
acronym: result.Acronym
});
});
doNextSteps();
},
function (error) {
console.log(error);
});
}
And here my latest Try:
function doNextSteps() {
//Create a HTML Table element.
var table = document.createElement("TABLE");
table.border = "1";
//Get the count of columns and rows.
var columnCount = departments.length;
var rowCount = countries.length;
//Add the header row.
var row = table.insertRow(-1);
for (var i = 0; i < columnCount; i++) {
var headerCell = document.createElement("TH");
headerCell.innerHTML = columnCount[0];
row.appendChild(headerCell);
}
//Add the data rows.
for (var i = 1; i < countries.length; i++) {
row = table.insertRow(-1);
for (var j = 0; j < rowCount; j++) {
var cell = row.insertCell(-1);
cell.innerHTML = rowCount[0];
}
}
var dvTable = document.getElementById("dvTable");
dvTable.innerHTML = "";
dvTable.appendChild(table);
}
But wont work the only thing i get is nothing or undefined. And i have no clue why becouse its the first time i try to generate a HTML Table with javascript. So any help would be great.
Thx for your Time and Help.
Related
I have a Laravel route returning a JSON, and I have a JS file that dynamically generates a table with the results in a JSON.
I just need to use this JSON in my JS table. That's all.
JS code (registroCarros should receive the value from the JSON, route or whatever)
function CreateTableFromJSON() {
var registroCarros = []
// EXTRAI VALOR PARA O HEADER HTML
var col = [];
for (var i = 0; i < registroCarros.length; i++) {
for (var key in registroCarros[i]) {
if (col.indexOf(key) === -1) {
col.push(key);
}
}
}
// CREATE TABLE
var table = document.createElement("table");
table.id = 'myTable';
var tr = table.insertRow(-1); //ROW.
for (var i = 0; i < col.length; i++) {
var th = document.createElement("th"); //HEADER.
th.innerHTML = col[i];
tr.appendChild(th);
}
for (var i = 0; i < col.length; i++) {
var td1 = document.getElementsByTagName("tr"); //HEADER.
td1.id="teste;"
}
// ADD JSON IN TABLE AS ROWS.
for (var i = 0; i < registroCarros.length; i++) {
tr = table.insertRow(-1);
for (var j = 0; j < col.length; j++) {
var tabCell = tr.insertCell(-1);
tabCell.innerHTML = registroCarros[i][col[j]];
}
}
var divContainer = document.getElementById("showData");
divContainer.innerHTML = "";
divContainer.appendChild(table);
}
My Controller (dbtest is a function in my model that have the SELECT im using):
public function returnJSON()
{
$teste = new user();
return response()->json(($teste->dbtest()));
}
and my route:
Route::get('returnJSON', 'App\Http\Controllers\Controller#returnJSON', ['names' => 'returnJSON']);
all I need is to use this route in my JavaScript.
Your Controller
public function returnJSON()
{
$teste = new user();
return response()->json($teste->dbtest());
}
Then your Route should look like this:
Route::get(
'returnJSON', // URL
'App\Http\Controllers\Controller#returnJSON' // Controller
)->name('returnJSON'); // Route name
Then finally in your blade file (JS code), you can use it as:
// behind any event (e.g. button click or value change etc.)
fetch("{{ route('returnJSON') }}") // This is the route name given in your route
// OR fetch("{{ url('returnJSON') }}") // and this is the URL (either can be used)
.then(res => res.json())
.then(data => CreateTableFromJSON(data));
/* 🔴REMEMBER */
// Your "CreateTableFromJSON" function must require an argument
// so that it can take the response (returned JSON) in it
function CreateTableFromJSON(registroCarros = []) {
// EXTRAI VALOR PARA O HEADER HTML
var col = [];
for (var i = 0; i < registroCarros.length; i++) {
for (var key in registroCarros[i]) {
if (col.indexOf(key) === -1) {
col.push(key);
}
}
}
// CREATE TABLE
var table = document.createElement("table");
table.id = 'myTable';
var tr = table.insertRow(-1); //ROW.
for (var i = 0; i < col.length; i++) {
var th = document.createElement("th"); //HEADER.
th.innerHTML = col[i];
tr.appendChild(th);
}
for (var i = 0; i < col.length; i++) {
var td1 = document.getElementsByTagName("tr"); //HEADER.
td1.id="teste;"
}
// ADD JSON IN TABLE AS ROWS.
for (var i = 0; i < registroCarros.length; i++) {
tr = table.insertRow(-1);
for (var j = 0; j < col.length; j++) {
var tabCell = tr.insertCell(-1);
tabCell.innerHTML = registroCarros[i][col[j]];
}
}
var divContainer = document.getElementById("showData");
divContainer.innerHTML = "";
divContainer.appendChild(table);
}
NOTE
This JS code must be in your blade file otherwise you have to put exact URL in fetch, like: fetch('xyz.com/returnJSON')
Also verify if the controller & model is working fine and you're gettting proper data. You can do it in:
either Controller:
public function returnJSON()
{
$teste = new user();
$data = $teste->dbtest();
dd($data); // HERE
return response()->json($data);
}
or JS (in beginning of 'CreateTableFromJSON' function):
function CreateTableFromJSON(registroCarros = []) {
console.log(registroCarros); // HERE
...
}
Try this:
fetch('{{ route('returnJSON') }}')
.then((res) => res.json())
.then( data => CreateTableFromJSON(data))
And remove the empty array inside the function
function CreateTableFromJSON(registroCarros) {
//var registroCarros = [] remove this line
Change route:
Route::get('returnJSON', 'App\Http\Controllers\Controller#returnJSON')->name('returnJSON');
So, if I understand your code properly, the missing piece is just the question how you fetch remote data. This is how you do it:
fetch('returnJSON')
.then((res) => res.json())
.then(CreateTableFromJSON)
function CreateTableFromJSON(registroCarros) {
// ...
This is my code
data = [{
name: 'Yemen',
code: 'YE'
},
{
name: 'Zambia',
code: 'ZM'
},
{
name: 'Zimbabwe',
code: 'ZW'
}
];
function addKeyValue(obj, key, data) {
obj[key] = data;
}
var checkbox = document.createElement('input');
checkbox.type = "checkbox";
checkbox.name = "key";
checkbox.id = "id";
newinfo = data.map(function(person) {
return addKeyValue(person, 'checkbox', (checkbox)); });
var columnHeadings = Object.keys(data[0]);
var columnCount = columnHeadings.length;
var rowCount = data.length;
var table = document.createElement('table');
document.getElementById("data-list").appendChild(table);
var header = table.createTHead();
var row = header.insertRow(-1);
for (var i = 0; i < columnCount; i++) {
var headerCell = document.createElement('th');
headerCell.innerText = columnHeadings[i].toUpperCase();
row.appendChild(headerCell);
}
var tBody = document.createElement('tbody');
table.appendChild(tBody);
for (var i = 0; i < rowCount; i++) { // each row
var checkbox = document.createElement('input');
row = tBody.insertRow(-1);
for (var j = 0; j < columnCount; j++) { // each column
var cell = row.insertCell(-1);
cell.setAttribute('data-label', columnHeadings[j].toUpperCase());
var obj = data[i];
cell.innerText = obj[columnHeadings[j]];
}
}
In a tabular format I do have to get checkboxes with the json data. So firstly I have defined my json and then I have append checkboxes for each row.I am planning to add check boxes in every json object. But in my final output it is giving [object HTMLInputElement] instead of a checkbox.
You are adding the element object to your newinfo array, if you want the html for it you need to add it to the dom which it looks like you want to do at some point later in your code, to do this you would for example do document.body.appendChild(checkbox) if you wanted to add the checkbox to body.
I have a function building a dynamic table. I'm having trouble figuring out how to set each column to a different data set from the database. Right now it just shows the same value in each column.
A little background. I'm building a table with 6 columns and lots of rows (all depends how much data the database has). Right now it's only showing one column in all of the 6 columns, so they repeat.
How can I set each column to a different value for the 6 columns?
function addTable() {
var len = errorTableData.length;
var myTableDiv = document.getElementById("myDynamicTable");
var table = document.createElement('TABLE');
table.border='1';
table.id = "dataTable";
var tableBody = document.createElement('TBODY');
table.appendChild(tableBody);
for (var i=0; i<len; i++){
var tr = document.createElement('TR');
tr.className = "rowEditData";
tableBody.appendChild(tr);
for (var j=0; j<6; j++){
var countyName = errorTableData['CountyName'][i];
var stateName = errorTableData['StateName'][i];
var td = document.createElement('TD');
td.className = "mdl-data-table__cell--non-numeric";
td.appendChild(document.createTextNode(countyName));
td.appendChild(document.createTextNode(stateName));
tr.appendChild(td);
}
}
myTableDiv.appendChild(table);
}
Here is the ajax call:
function triggerDataTable(index) {
// Make AJAX requests for model systems
$.ajax({
type: "POST",
url: "qry/getAllData.php",
async: true,
dataType: "html",
data: {ErrorOptions: control.settings.errorOptions},
success: function (result) {
//console.warn(result);
errorData = JSON.parse(result);
//loop through data
var len = errorData.length;
for(i=0; i<len; i++) {
if ('VersionKey' in errorData[i]) {
vKey = (errorData[i]['VersionKey']);
} else if ('ErrorCode' in errorData[i]) {
var errorCode = (errorData[i]['ErrorCode']);
} else if ('SourceKey' in errorData[i]) {
var sourceKey = (errorData[i]['SourceKey']);
} else { //data here
errorTableData = errorData[i];
}
}
addTable();
}
});
}
The errorData is the data from the database. As you can see I've tried to add 2 variables but when I do that it just puts both of them in the same box and repeats throughout the whole table.
It looks like you are printing the exact same data 6 times for each row. You create a td element, then add country and state names to it, but the variable you are using for the index on your data set is coming from your outer loop, so on the inner loop it never changes, and you are literally grabbing the same value every time:
function addTable() {
var len = errorTableData.length;
var myTableDiv = document.getElementById("myDynamicTable");
var table = document.createElement('TABLE');
table.border='1';
table.id = "dataTable";
var tableBody = document.createElement('TBODY');
table.appendChild(tableBody);
for (var i=0; i<len; i++){
// You set i here, presumably to get each row in your dataset
var tr = document.createElement('TR');
tr.className = "rowEditData";
tableBody.appendChild(tr);
for (var j=0; j<6; j++){
var countyName = errorTableData['CountyName'][i];
var stateName = errorTableData['StateName'][i];
// Above, you are using i, not j
var td = document.createElement('TD');
td.className = "mdl-data-table__cell--non-numeric";
td.appendChild(document.createTextNode(countyName));
td.appendChild(document.createTextNode(stateName));
tr.appendChild(td);
}
}
myTableDiv.appendChild(table);
}
It would be easier to help if you could post some json with the data you are getting from the DB
Based on the edit on your post and looking at the success callback, I think you have small problem that can be easily fixed:
First, initialize an empty array for errorTableData
success: function (result) {
errorTableData = [];
In your if/else block:
} else { //data here
errorTableData = errorData[i];
}
Should be:
} else { //data here
errorTableData[i] = errorData[i];
}
Then in your inner loop:
var countyName = errorTableData['CountyName'][i];
var stateName = errorTableData['StateName'][i];
Becomes:
var countyName = errorTableData[i]['CountyName'][j];
var stateName = errorTableData[i]['StateName'][j];
This is just a guess because I can't see the actual data.
I have a problem in displaying the borders of my table correctly ,I work with jsPDF library ,this is the result that I get :
this is my code that selecet every row and display the data:
function tableToJson(table) {
var data = [];
// first row needs to be headers
var headers = [];
for (var i=0; i<table.rows[0].cells.length,i<5; i++) {
headers[i] = table.rows[0].cells[i].innerHTML.toLowerCase().replace(/ /gi,'');
}
data.push(headers);
// go through cells
for (var i=1; i<table.rows.length;i++) {
var tableRow = table.rows[i];
var rowData = {};
for (var j=0; j<tableRow.cells.length,j<5 ; j++) {
rowData[ headers[j] ] = tableRow.cells[j].innerHTML;
}
data.push(rowData);
}
return data;
}
function callme(){
var table = tableToJson($('#table').get(0));
var doc = new jsPDF('l','pt','letter',true);
$.each(table, function(i, row){
$.each(row, function(j,cell){
if(j=="email"){
doc.cell(1,10,190,20,cell,i);
}
else{
doc.cell(1,10,100,20,cell,i);
}
});
});
thanks for help
I am stuck. I am retrieving data from parse.com and trying to dynamically add them to their respective fields. What am I messing up on? I can console.log the data, so my get request is working. Thank you.
var parseData = function() {
var orderform = Parse.Object.extend("OrderForm");
var query = new Parse.Query(orderform);
query.find({
success: function (results) {
var tableRow = $('<tr />', {class: 'tableRows'});
var restaurantListP = [];
var tdId = [];
var tdEmail = [];
var tdMenuItems = [];
var tdNotes = [];
var tdPhoneNumber = [];
var table = $('#orderTable > tbody');
function newRow($table, cols){
$row = $('<tr/>');
for (var i = 0; i < cols.length; i++) {
$col = $('<td/>');
$col.append(cols[i]);
$row.append($col[i]);
}
table.append($row);
}
results.forEach(function (r, i) {
// tdId = $('<td />', { "id": r.id });
tdEmail = $('<td />', {email_address: r.attributes.email_address });
tdMenuItems = $('<td />', {menu_items: r.attributes.menu_items });
tdNotes = $('<td />', {notes: r.attributes.notes});
tdPhoneNumber = $('<td />', {phone_number: r.attributes.phone_number});
newRow(table,[tdId,tdEmail,tdMenuItems,tdNotes,tdPhoneNumber]);
// $('#orderTable > tbody').append(tableRow).append(restaurantListP[0]);
console.log(tdMenuItems);
console.log(tdEmail);
});
http://jsfiddle.net/DaveDH2/tb6d7w81/
There are two major errors:
id="orderTable" is set for <tbody>, not to <table>, so $('#orderTable > tbody') finds nothing. You should either move id="orderTable" to <table>, or rewrite selector to var table = $('#orderTable').
newRow function works incorrectly: it wraps already created <td> with another <td>, making <tr> html code incorrect. This function should be rewritten in something like this:
function newRow($table, cols)
{
var $row = $('<tr/>');
for (var i = 0; i < cols.length; i++)
{
$row.append(cols[i]);
}
$table.append($row);
}
Updated fiddle.