I would like to fill an HTML table with a JavaScript array.
But, it doesn't work and I don't know why, my "innerHTML" is not interpreted.
My variable contains the good value, but when I do this :
document.getElementById("title").innerHTML = title;
It doesn't work.
This is my code:
var title = "";
var link = "";
var date = "";
var image = "";
function get_posts() {
var xhr = new XMLHttpRequest();
xhr.open("GET", "my_url");
xhr.onload = function () {
if (xhr.responseText == 0) {
alert("Vous n'avez poster aucun post");
} else {
var posts_array = JSON.parse(xhr.responseText);
for (var i = 0; i < posts_array.length; i++)
{
title = posts_array[i][0];
link = posts_array[i][1];
date = posts_array[i][2];
image = posts_array[i][3];
}
document.getElementById("title").innerHTML = title;
}
}
xhr.send();
}
This is my HTML :
<table id="posts">
<tr>
<th id="test">Titre</th>
<th>Lien</th>
<th>Date</th>
<th>Image</th>
</tr>
<tr>
<td id="title"></td>
<td id="link"></td>
<td id="date"></td>
<td id="image"></td>
</tr>
</table>
You're assigning the value of title inside your loop and then setting the innerHTML of an individual cell to title. Assuming your responseText is formatted correctly, the posts table will only ever contain the last element in your array. It seems like you need to create a new table row for each item in posts_array and add it to the posts table to get your intended result.
e.g.
var t = "";
for (var i = 0; i < posts_array.length; i++){
var tr = "<tr>";
tr += "<td>"+posts_array[i][0]+"</td>";
tr += "<td>"+posts_array[i][1]+"</td>";
tr += "<td>"+posts_array[i][2]+"</td>";
tr += "<td>"+posts_array[i][3]+"</td>";
tr += "</tr>";
t += tr;
}
document.getElementById("posts").innerHTML += t;
You have 3 errors in your code.
You overriding title, link, date and image on each iteration.
You setting only title, I think you want to set all data.
(Posible error) You setting only 1 post into table, probably you
want to see them all.
Easiest (and most common) way to create table from array is build HTML string (with table markup), and append it to table. Unfortunately IE do not support appending html into table, to solve this you may use jquery (it will create Elements from html and append them).
Example:
var posts_array = JSON.parse(xhr.responseText);
var columns = ['title', 'link', 'date', 'image']
var table_html = '';
for (var i = 0; i < posts_array.length; i++)
{
//create html table row
table_html += '<tr>';
for( var j = 0; j < columns.length; j++ ){
//create html table cell, add class to cells to identify columns
table_html += '<td class="' +columns[j]+ '" >' + posts_array[i][j] + '</td>'
}
table_html += '</tr>'
}
$( "#posts" ).append( table_html );
Another way is to use table dom api, this will not require jQuery:
var posts_array = JSON.parse(xhr.responseText);
var columns = ['title', 'link', 'date', 'image']
var table = document.getElementById('posts');
for (var i = 0; i < posts_array.length; i++)
{
var row = table.insertRow( -1 ); // -1 is insert as last
for( var j = 0; j < columns.length; j++ ){
var cell = row.insertCell( - 1 ); // -1 is insert as last
cell.className = columns[j]; //
cell.innerHTML = posts_array[i][j]
}
}
It doesn't work for me.
I want to display wordpress posts into an HTML table.
My JS :
function get_posts() {
var xhr = new XMLHttpRequest();
xhr.open("GET", "myUrl");
xhr.onload = function () {
if (xhr.responseText == 0) {
alert("Vous n'avez poster aucun post");
} else {
var posts_array = JSON.parse(xhr.responseText);
var columns = ['title', 'link', 'date', 'image']
var table_html = '';
for (var i = 0; i < posts_array.length; i++)
{
//create html table row
table_html += '<tr>';
for (var j = 0; j < columns.length; j++) {
//create html table cell, add class to cells to identify columns
table_html += '<td class="' + columns[j] + '" >' + posts_array[i][j] + '</td>'
}
table_html += '</tr>'
}
}
$("#posts").append(table_html);
}
xhr.send();
}
My HTML :
<table id="posts">
<tr>
<th id="test">Titre</th>
<th>Lien</th>
<th>Date</th>
<th>Image</th>
</tr>
</table>
My Web service (i'm using wordpress) :
global $current_user;
if(is_user_logged_in){
$current_user = wp_get_current_user();
}
$array = array();
$posts_array = array('author' => $current_user->ID, "post_type" => "alertes", "orderby" => "date", "order" => "DESC", "post_status" => "publish", "posts_per_page" => "10");
$posts = new WP_Query($posts_array);
if($posts->have_posts()){
while($posts->have_posts()){
$posts->the_post();
$post_array = array(get_the_title(), get_the_permalink(), get_the_date(), wp_get_attachment_url(get_post_thumbnail_id()));
array_push($array, $post_array);
}
echo json_encode($array);
}
else {
echo '0';
}
Related
Im trying to do something similar to this answer: How to add multiple rows to a jQuery DataTable from a html string
The only difference is:
I need to add multiple values that i will get from a text area. The first part works perfectly.
function Gen(){
var data = require('../../cases/config.json');
var tableHeaders;
var cantidad = 0;
$.each(data.Ge[0].Data, function(i, val){
cantidad += 1
tableHeaders += "<th>" + val + "</th>";
});
// Header
$("#tabGen").empty();
$("#tabGen").append('<thead><tr>' + tableHeaders + '</tr></thead>');
var t = $('#tabGen').DataTable({
"scrollY": 200,
"scrollX": true,
rowReorder: true,
autoFill: true,
select:true,
stateSave: true
});
This second part when doing the t.row.add($(info)).draw(); it doesn't appear all the data that i need to show. So when I check out the other answer I saw that I can add a single row from an html string. So I don't know how can I add multiple values inside of the table.
$('#excel').on( 'click', function () {
var inf = $('textarea[name=excel_data]').val();
var rows = inf.split("\n");
for(var y = 0; y < rows.length; y++) {
var cells = rows[y].split("\t");
for(var x in cells) {
var info = '<td><input type="text" id="inputTextAg'+x+'" name="inputTextAg'+x+'" value="'+cells[x]+'" draggable="true" "></td>'
t.rows.add($(info)).draw();
}
}
});
}
Thanks!
Try this:
$('#excel').on( 'click', function () {
var inf = $('textarea[name=excel_data]').val();
var rows = inf.split("\n");
for(var y = 0; y < rows.length; y++) {
var cells = rows[y].split("\t");
var info = '<tr>';
for(var x in cells) {
info += '<td><input type="text" id="inputTextAg'+x+'" name="inputTextAg'+x+'" value="'+cells[x]+'" draggable="true" "></td>';
}
info += '</tr>';
t.rows.add($(info)).draw();
}
});
}
I'm doing a function that creates a table in JS.
I create a variable table_row fill it and then add table_layout.appendChild(table_row); it to the table_layout element.
Next, I clean it table_row through innerHTML='', but when cleaning, the variable that I ALREADY added to the element table_layout is also cleared.
Why is this happening?
Should the added element be cleared?
How can this be avoided?
Look at the CODE.
var columns = ["col1", "col2", "col3"];
var rows = 5;
function Table() {
var table_layout = document.createElement("table");
var table_row = document.createElement("tr");
for (var i = 0; i < columns.length; i++) {
// main row
table_row.innerHTML += "<th>" + columns[i] + "</th>";
}
table_layout.appendChild(table_row); //add in table element
// table_row.innerHTML = ""; //If you uncomment this line, then we get an empty output!
//refresh table_row html, that would generate a new line
//But when cleaning. Cleared in the previously added item in table_layout .... how??
// for (var j = 0; i < columns.length; j++) {
// table_main_row.innerHTML += '<td></td>';
// }
// for (var i = 0; i < rows; i++) {
// table_layout.appendChild(table_row);
// }
return table_layout;
}
var div = document.getElementById("qqq");
div.appendChild(Table());
#qqq {
background: red;
}
<div id="qqq"></div>
The table_row variable contains a reference. You will need to create a new element for each row.
// creates a DOM Element and saves a reference to it in the table_row variable
var table_row = document.createElement("tr");
// updates the DOM Element through the reference in the table_row variable
table_row.innerHTML += "<th>" + columns[i] + "</th>";
// still references the DOM Element, so you are clearing its content
// table_row.innerHTML = "";
You will need to . . .
// create a new DOM Element to use
table_row = document.createElement("tr");
// then update its contents
table_main_row.innerHTML += '<td></td>';
. . . for each iteration.
See JavaScript on MDN for tutorials, references, and more.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" language="javascript">
var columns = ["col1", "col2", "col3"];
var rows = 5;
function createNewRow(headerRow)
{
var newRowElem = null;
try
{
newRowElem = document.createElement("tr");
for (var i = 0; i < columns.length; i++)
{
if(headerRow) newRowElem.innerHTML += "<th>" + columns[i] + "</th>";
else newRowElem.innerHTML += "<td>" + columns[i] + "</td>";
}
}
catch(e)
{
alert("createNewRow Error" + e.Message);
}
finally
{
}
return newRowElem;
}
function Table()
{
var table_layout = null;
try
{
table_layout = document.createElement("table");
// Create Header Row
table_layout.appendChild(createNewRow(true));
// Create Other Rows
for (var i = 0; i < rows; i++)
{
table_layout.appendChild(createNewRow(false));
}
}
catch(e)
{
alert("Table Error: " + e.Message);
}
finally
{
}
return table_layout;
}
</script>
<style>
#qqq {
background: red;
}
</style>
</head>
<body>
<div id="qqq"></div>
<script type="text/javascript" language="javascript">
var div = document.getElementById("qqq");
div.appendChild(Table());
</script>
</body>
</html>
I did so.
var table_layout = document.createElement('table');
table_layout.setAttribute('id', 'main_table');
table_layout.setAttribute('border', '1');
var row = document.createElement('tr');
row.setAttribute('class', 'main_row');
for (var i = 0; i < this.fields.length; i++) { // строка с именами столбцов
var th = document.createElement('th');
th.setAttribute('class', 'cell_name');
th.innerHTML = this.fields[i];
row.appendChild(th);
}
table_layout.appendChild(row); //добавляем
row = document.createElement('tr'); // очищаем от старых элементов строку (переопределяем)
row.setAttribute('class', 'table_row');
var td = document.createElement('td');
td.setAttribute('class', 'table_cell');
// td.setAttribute('ondblclick', 'input_func()');
td.addEventListener('click', function () {
alert();
});
td.innerHTML='000';
for (var j = 0; j < this.fields.length; j++) { // создаем строку с N-количеством ячеек
row.appendChild(td.cloneNode(true));
}
for (var i = 0; i < this.rows; i++) { // Добавляем её есколько раз через клона
table_layout.appendChild(row.cloneNode(true));
}
But then redistribution with functions for the table.
var table_layout = document.createElement('table');
table_layout.setAttribute('id', 'main_table');
table_layout.setAttribute('border', '1');
var row = table_layout.insertRow(0);
var cell;
for (var j = 0; j < this.fields.length; j++) {
cell = row.insertCell(j);
cell.outerHTML = '<th>' + this.fields[j] + '</th>';
cell.className = 'cell_name';
}
for (var i = 0; i < this.rows; i++) {
row = table_layout.insertRow(i + 1);
row.className = 'row_table';
for (var n = 0; n < this.fields.length; n++) {
cell = row.insertCell(n);
// cell.innerHTML = '00';
cell.className = 'table_cell';
cell.innerHTML = ' ';
}
}
return table_layout;
I am trying to sum a table column total.
Here is an example of only two column for test purposes. I want to calculate table column's item total using a javascript loop.
How to create the loop if we don't know how many rows and columns are inside in table? I hope you understand what I mean and also hope for your kindly suggestion.
<p><b>Student at Stanford University 2013-2014</b></p>
<table><tr><th>Faculty (Subject)</th><th>Student 2013</th><th>Student 2014</th></tr></table>
<table id="sdtable">
<tr><th>Business</th><td>12922</td><td>11420</td></tr>
<tr><th>Earth Sciences</th><td>4320</td><td>4611</td></tr>
<tr><th>Education</th><td>14560</td><td>13490</td></tr>
<tr><th>Engineering</th><td>8750</td><td>9863</td></tr>
<tr><th>Humanities & Sciences</th><td>7819</td><td>7219</td></tr>
<tr><th>Medicine</th><td>5219</td><td>4200</td></tr>
</table>
<button onclick="Calculate()">Calculate</button>
<div id="Studentf" class="Studentf"></div>
<div id="Students" class="Students"></div>
<div id="Studentt" class="Studentt"></div>
and
var ftable = document.getElementById("sdtable");
var i= 0;
var sumFirst=0;
var sumSecond=0;
var sumTotal=0;
function Calculate(){
for (i=0;i<ftable.rows.length; i++){
sumFirst=sumFirst+parseInt(ftable.rows[i].cells[1].innerHTML);
sumSecond=sumSecond+parseInt(ftable.rows[i].cells[2].innerHTML);
}
sumTotal=sumFirst+sumSecond;
document.getElementById("Studentf").innerHTML +="<b>Student in 2013 = </b>" +sumFirst;
document.getElementById("Students").innerHTML +="<b>Student in 2014 = </b>" +sumSecond;
document.getElementById("Studentt").innerHTML +="<b>Total Student = </b>" +sumTotal;
}
The key here is that you need to use cells collection to get number of columns that can change when you add new years to the table. You will also have to dynamically create elements for summary information per year.
Here is an example:
var ftable = document.getElementById("sdtable");
var i = 0;
var sumFirst = 0;
var sumSecond = 0;
var sumTotal = 0;
function Calculate() {
var rows = ftable.tBodies[0].rows,
header = ftable.tHead.rows[0],
cells = ftable.tBodies[0].rows[0].cells,
years = [];
for (var i = 0; i < rows.length; i++) {
for (var j = 1; j < cells.length; j++) {
if (!years[j]) years[j] = 0;
years[j] += parseInt(rows[i].cells[j].innerHTML);
}
}
sumTotal = years.reduce(function(prev, curr) {
return prev + curr;
}, 0);
var sum = document.getElementById("sum");
sum.innerHTML = '';
for (var j = 1; j < cells.length; j++) {
console.log(header.cells[j])
sum.insertAdjacentHTML('afterbegin', '<p><b>' + header.cells[j].innerHTML + '</b> = ' + years[j] + '</p>');
}
sum.insertAdjacentHTML('beforeend', "<b>Total Student = </b>" + sumTotal);
}
Demo: http://jsfiddle.net/x2sscpxL/1/
The table should probably look more like:
<table>
<thead>
<tr><th>Faculty (Subject)</th><th>Student 2013</th><th>Student 2014</th></tr>
</thead>
<tbody id="sdtable">
<tr><th>Business</th><td>12922</td><td>11420</td></tr>
<tr><th>Earth Sciences</th><td>4320</td><td>4611</td></tr>
<tr><th>Education</th><td>14560</td><td>13490</td></tr>
...
</tbody>
<tfoot>
<tr><th>Totals:</th><th></th><th></th></tr>
</table>
to split the header, body and footer into separate table sections. The function should then be like:
function calculate(){
// Get a reference to the tBody
var tBody = document.getElementById('sdtable');
if (!tBody) return;
var row, rows = tBody.rows;
var cell, cells;
var cellTotals = {};
// For each row in the body
for (i=0, iLen=rows.length; i<iLen; i++) {
row = rows[i];
cells = row.cells;
// Add the cells in each column, starting on the second column
// i.e. starting with cell index 1
for (var j=1, jLen=cells.length; j<jLen; j++) {
cell = cells[j];
if (j in cellTotals) {
cellTotals[j] += Number(cell.textContent || cell.innerText);
} else {
cellTotals[j] = Number(cell.innerHTML);
}
}
}
// Write the totals into the footer
var tFoot = tBody.parentNode.tFoot;
row = tFoot.rows[0];
for (var k=1; k<jLen; k++) {
row.cells[k].innerHTML = cellTotals[k];
}
}
Note that by convention, variables with a name starting with a capital letter are reserved for constructors (though constants usually are all caps).
Here is calculation of table witn n rows and n columns
Note: header cells wrapped in thead section
var ftable = document.getElementById("sdtable");
var tbody = ftable.getElementsByTagName("tbody")[0]
var columnsCount = ftable.rows[0].cells.length;
var sumTotal = [];
for(i=0; i<columnsCount;i++)
sumTotal.push(0); //here initialize with zero
function Calculate(){
for (i=0;i<tbody.rows.length; i++){
for (j=0; j<columnsCount; j++)
if (tbody.rows[i].cells[j] && tbody.rows[i].cells[j].innerHTML)
sumTotal[j] += parseInt(tbody.rows[i].cells[j].innerHTML);
}
return sumTotal;
}
sumTotal = Calculate();
tfootrow = ftable.tFoot.rows[0];
console.log(tfootrow)
for(i=0; i<sumTotal.length; i++){
tfootrow.insertCell(i).innerHTML = sumTotal[i];
}
<table id="sdtable">
<thead>
<tr>
<th>Business</th>
<th>Earth Sciences</th>
<th>Education</th>
<th>Engineering</th>
<th>Humanities & Sciences</th>
<th>Medicine</th>
</tr>
</thead>
<tbody>
<tr><td>12922</td><td>11420</td></tr>
<tr><td>4320</td><td>4611</td></tr>
<tr><td>14560</td><td>13490</td></tr>
<tr><td>8750</td><td>9863</td></tr>
<tr><td>7819</td><td>7219</td></tr>
<tr><td>5219</td><td>4200</td></tr>
<tr><td></td><td>1</td><td>2</td></tr>
</tbody>
<tfoot>
<tr></tr>
</tfoot>
</table>
I have a unique problem that I hope someone can help with. I have a page that pulls data from a controller with AJAX and presents it to this function to construct a table:
// make rows in table from json data
function makeTableRows() {
if (jsonTableData != null) {
tbl = null;
tbl = createTable('tableResults');
// constructHeader(tbl, 'left', jsonTableData[0]);
newHeader(tbl, 'left', jsonTableData[0]);
var totalItems = jsonTableData.length;
var topItem;
topItem = 0;
if ((lastItem + perpage) > totalItems) {
topItem = totalItems;
$(".btnNext").prop('disabled', true);
}
else {
topItem = lastItem + perpage;
}
for (var i = lastItem; i <= topItem - 1; i++) {
makeTableRow(tbl, jsonTableData[i], 'left', true, 'showTourDetails(' + jsonTableData[i]["TransactionID"] + ',' + i + ')', 0);
}
$("#divSearchResults").html(tbl);
makePagesLabel();
makeTableFooter(tbl);
}
}
the function inside the separate file is this:
function constructHeader(table, alignment, firstRow) {
if (firstRow != null) {
var thead = document.createElement('thead');
table.appendChild(thead);
var tr = document.createElement('tr');
for (var key in firstRow) {
var header = key.match(/[A-Z][a-z]*/g);
var newHeader = '';
for (var i = 0; i <= header.length - 1; i++) {
newHeader += header[i] + ' ';
}
var th = document.createElement('th');
var text = document.createTextNode(newHeader);
th.appendChild(text);
th.style.textAlign = alignment;
th.style.cursor = 'pointer';
th.setAttribute('title', "Sort by " + newHeader);
th.onclick = function () {
var rows = $(table).find('tbody').find('tr').toArray().sort(comparer($(this).index()));
this.asc = !this.asc;
if (!this.asc) {
rows = rows.reverse();
}
for (var j = 0; j < rows.length; j++) {
$(table).append(rows[j]);
}
$(table).find('tbody').find('tr:even').css("background-color", "#dae5f4");
$(table).find('tbody').find('tr:odd').css("background-color", "#b8d1f3");
};
tr.appendChild(th);
}
thead.appendChild(tr);
}
}
Basically the function creates a sort process for the header of each column. After the sort of the column, I want to reapply the zebra striping that is applied with the class of the table. If I don't try to reapply I end up with the striping all messed up. Now, the problem is that if I copy the function into the .cshtml page and give it the name of 'newheader', the re-striping works fine. It does not work in the separate JS file and I cannot figure out why. Anyone have any clues?
HeaderA HeaderB HeaderA HeaderB
stuff 232 hey 3434
world 033 boy 221
bat 435 girl 930
This table is dynamic and gets populated live. Here's my JS code, but the logic is not working correctly. I need to tell it that every 2 columns is a new record, and make a new row every 4th column. Here's what I have so far:
function html_data(data) {
var html = '';
$.each(data, function (index, value) {
if ((index+1) % 4 == 0 && index != 0) {
html += '<td>'+value+'</td>';
html += '</tr>'
} else if ((index+1) % 5 == 0) {
html += '<tr>';
html += '<td>'+value+'</td>';
} else {
html += '<td>'+value+'</td>';
}
html += '</tr>';
});
return html;
}
Obviously the above code is completely wrong, but that's all I have so far. If I can the get the mod logic, I can fill in the blanks.
Try this http://jsfiddle.net/G3JK5/
HTML
<table id="table">
<tr>
<th>HeaderA</th>
<th>HeaderB</th>
<th>HeaderA</th>
<th>HeaderB</th>
<th>HeaderA</th>
<th>HeaderB</th>
</tr>
</table>
<input type="button" id="btn" value="Add some random data" />
Javascript
//Sample usage
var tbl = new weirdTable('table');
document.getElementById('btn').addEventListener('click', function(){
tbl.addData([
parseInt(Math.random() * 100),
parseInt(Math.random() * 100)
]);
});
weirdTable
function weirdTable(tableId){
var _me = null;
var _currentIndex = 0;
var _colCount = 0;
var _lastRowIndex = 0;
var construct = function(tableId){
_me = document.getElementById(tableId);
_colCount = _me.rows[0].cells.length;
_currentIndex = _colCount;
};
this.addData = function(data){
var row = _me.rows[_lastRowIndex];
//or var data = arguments;
for(var i = 0; i < data.length; i++){
if(_currentIndex >= _colCount){
_lastRowIndex++;
_currentIndex = 0;
row = _me.insertRow(_lastRowIndex);
}
row.insertCell(_currentIndex).innerText = data[i];
_currentIndex++;
}
};
construct(tableId);
}
Unless I'm missing something, you can just do this:
if (index%4===0) { // start of a row
html += '<tr>';
}
html += '<td>'+value+'</td>';
if (index%4===3) { // end of row
html += '</tr>';
}