How can I populate my HTML table with an array of data? - javascript

I'm building a table with HTML and then have created a function which allows me to select a cell. I also have a text field, with a function which will both change the innerText of the cell to the value in the text field and push that value into an array of the data in each table cell. I am then saving it to localStorage.
Here I encounter my error: how can I properly retrieve the data from the localStorage variable and repopulate the table with the values in the array?
Here's my code
omitting the table creation, textEntering, functions because they appear to be working fine
function save() {
localStorage.setItem("tblArrayJson", JSON.stringify(tblArray));
document.getElementById("lblInfo").innerHTML = "Spreadsheet saved.";
}
This is working because in a test function I can print the tblArrayJson in an alert. Next I am trying to load the data back to the table:
function loadSheet() {
var loadedData = JSON.parse(localStorage.getItem("tblArrayJson"));
var loadedTable = document.getElementById("SpreadsheetTable");
var currRow, cell;
alert("the retrieved JSON string contains: " + loadedData);
for (var i = 0; currRow = loadedTable.rows[i]; i++) {
for (var j = 0; cell = currRow.cells[j]; j++) {
cell.innerHTML = loadedData.shift();
}
}
}
The alert displaying the loadedData is working correctly. So what is it about my loop that is failing to insert the array values back into the table? They just stay blank.
Is there a problem with the way I'm using the function? Here is my button with the onclick:
<input id="btnLoad" type="button" onclick="loadSheet();" value="Load" />

localStorage is an object.
A loop through an object for(var key in object) {} is different to a loop through an array for(var i = 0; i < arr.length; i += 1) {}.
If the data looks like
var loadedData = {
0: ["cell1", "cell2", "cell3"],
1: ["cell1", "cell2", "cell3"]
}
the loops should look like
for(var key in loadedData) {
var row = loadedTable.insertRow();
for(var i = 0; i < loadedData[key].length; i += 1) {
var cell = row.insertCell(i);
cell.innerHTML = loadedData[key][i];
}
}
Example
var loadedData = {
0: ["cell1", "cell2", "cell3"],
1: ["cell1", "cell2", "cell3"]
}
function loadSheet() {
//var loadedData = JSON.parse(localStorage.getItem("tblArrayJson"));
var loadedTable = document.getElementById("SpreadsheetTable");
for (var key in loadedData) {
var row = loadedTable.insertRow();
for (var i = 0; i < loadedData[key].length; i += 1) {
var cell = row.insertCell(i);
cell.innerHTML = loadedData[key][i];
}
}
}
loadSheet();
<table id="SpreadsheetTable"></table>

Your for loop is missing the terminating condition. I added that to mine, you're free to modify to fit your needs.
var data = {
0: ["cell1", "cell2", "cell3"],
1: ["cell4", "cell5", "cell6"]
};
// localStorage.tblArrayJson = JSON.stringify(loadedData);
function loadSheet() {
// var data = JSON.parse(localStorage.tblArrayJson);
var table = document.getElementById("SpreadsheetTable");
var row, cell;
// Used Object.keys() to get an array of all keys in localStorage
for (var key of Object.keys(data)) {
row = table.insertRow();
for (var i = 0; i < data[key].length; i++) {
cell = row.insertCell(i);
cell.innerHTML = data[key][i];
}
}
}
loadSheet();
<table id="SpreadsheetTable"></table>

Related

When create checkbox in JavaScript got [object HTMLInputElement]

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.

How to add different columns to a dynamic table from database with javascript

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.

Generate HTML Table with 2 javascript Arrays

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.

Read user input matrix to twodimensional array

I create a form with matrix like this:
for(var i = 0; i < rows; i++)
{
for(var j = 0; j < columns; j++)
{
var input = $('<input>')
.attr({
class: 'matrix_cell',
value: 0});
form.appendChild(input[0]);
}
var br = $('<br>')[0];
form.appendChild(br);
}
And I want to read a matrix that user inputted to two-dimensional array and then pass it to php file in ajax query.
I tried this way:
function getMatrix(){
var matrix_row = []
$("#matrix_form").find("input").each(function(i){
var value = $(this).val();
if (!isNaN(value)){
matrix_row[i] = value;
}
});
return matrix_row;
}
But it reads matrix to onedimensional array.
See http://jsfiddle.net/hcbLozd7/
function getMatrix(){
var matrix_row = [];
var ind = 0;
$("#frm").contents().each(function(i,e){ //for all contents in div
if (this.nodeName == "INPUT") //if it's input
{
if (!matrix_row[ind]){ //it matrix doesn't have a new array, push a new array
matrix_row.push([]);
}
matrix_row[ind].push($(this).val()); //add input value to array inside array
}
else{ //when element is br
ind++; //increment counter
}
});
return matrix_row;
}

How to print dynamic contents of array at different positions in HTML5

I have to fetch data from the PHP web service in an array and then display it on HTML page using JavaScript. I have used a for loop to do so. But it doesn’t render proper output. Due to innerHTML the output gets replaced. Please help with your suggestions. Here is my code:
function jsondata(data){
alert("JSONdata");
var parsedata = JSON.parse(JSON.stringify(data));
var main_category = parsedata["main Category"];
for (var i = 0; i <= main_category.length; i++) {
menu = JSON.parse(JSON.stringify(main_category[i]));
menu_id[i] = menu['mcatid'];
menu_title[i] = menu['mcattitle'];
menu_img[i] = menu['mcatimage'];
pop_array.push(menu_id[i], menu_title[i], menu_img[i]);
//alert(pop_array);
for (var i = 0; i < main_category.length; i++) {
alert("for start");
var category = document.createElement("li");
document.getElementById("mylist").appendChild(category);
//document.getElementById("mylist").innerHTML='<table><tr><td>'+pop_array[i]+'</td></tr></table>';
document.write(pop_array.join("<br></br>"));
alert("for end");
}
}
}
Although I don't get why pop_array was used here but I assume that you are trying to display the category info as a li tag.
You should set category.innerHTML instead of document.getElementById("mylist").innerHTML.
function jsondata(data){
var parsedata = JSON.parse(JSON.stringify(data));
var main_category = parsedata["main Category"];
for (var i = 0; i < main_category.length; i++) {
var menu = main_category[i];
var category = document.createElement("li");
category.innerHTML = menu['mcattitle']; // construct your own html here
document.getElementById("mylist").appendChild(category);
}
}

Categories