Dynamic creation of table for web service response in html js - javascript

Below is the code for displaying webservices json response using li,ul tags dynamically it works fine but i need the same for table using tr,td the main thing to be noted is i need to save the onclick data here which is data(doc1) .help please thanks in advance
ul = $('#mydemo1');
ul.html(null);
for (var i = 0; i <= result.length; i++)
{
var doc1 = result[i];
li = $('<li/>').html(doc1.Name).data(doc1);
li.append($('<br/>'));
li.append($('<hr>'));
ul.append(li);
}
<ul id="mydemo1" style="text-align:left;"> </ul>

Try this...
var tableelement= $('#mydemo1'); //where mydemo1 is the id of some table in DOM
for (var i = 0; i < result.length; i++) {
tableelement.append(createRow(result[i]));
}
function createRow(rowObject) { //dynamically adding rows to the Table where each row contains the name
var trElement = "<tr>";
trElement += "<td>" + rowObject.Name + "</td>";
return trElement;
}

Related

Nesting [innerHTML] in AngularJS

How can I 'nest' innerHTML bindings? Is it a sanitation problem?
I am using angular to create a website to play chess. I am dynamically creating a table and putting it into the component with: <div [innerHTML]="board | safeHTML"> where board with a string with the HTML for the table in and safeHTML is a pipe that bypasses sanitisation so the HTML isn't just read as a string. The code to generate the table is at the bottom of the post.
I would like to then be able to change the contents of each cell in the table.
Here is an example cell:
<td id="n${uniqueNumber}" class="board" [innerHTML]="boardValues.${uniqueNumber}">{{boardValues.${uniqueNumber}}}</td>
boardValues is an object that contains all of the cell data.
The table correctly displays when bound with [innerHTML] however the cells don't and [innerHTML] is displayed as an attribute (e.g. this image). Similarly {{boardValues.value}} shows up as plain text rather than the value.
How can I 'nest' innerHTML bindings? Is it a sanitation problem?
My html:
Running that doesn't work but it shows my main loops (the important one is generateBoard)
Here is a stack blitz project that sort of works but doesn't have formatting for some reason. Still shows my issue
generateBoard(n, playColour) {
var tblBuild = ""
var tblFooter = "<tr><td id=\"blank\"></td>"
for (var i = 0; i < 8; i++) {
tblFooter += `<th class="coordinates letters">${String.fromCharCode(97+i)}</th>`
}
tblFooter += "</tr>"
for (var i = 0; i <= n; i++) {
tblBuild += `<tr class="n${n-i+1}">`
tblBuild += `<th class="coordinates numbers">${n-i+1}</th>`
for (var j = 0; j <= n; j++) {
var idValue = `n${8*(n-i)+j}`
//want to assign the innerHTML to an object
tblBuild += `<td id="n${idValue}" class="board" [innerHTML]="boardValues.${idValue}">{{boardValues.${idValue}}}</td>`
}
tblBuild += ("</tr>")
}
var tbl = "<table id=\"board\" class= \"board " + playColour + "\"" + "<tbody>" + tblBuild + "</tbody>" + tblFooter + "</table>"
console.log(tbl)
return tbl
}
generateBoardValues(n) {
interface LooseObject {
[key: string]: any
}
var boardValues: LooseObject = {}
console.log("running generateBoardvalues")
console.log("n", n)
for (var i = 0; i <= n; i++) {
for (var j = 0; j <= n; j++) {
boardValues[`n${8*(n-i)+j}`] = `n${8*(n-i)+j}`
console.log("generating boardValues", boardValues[`n${8*(n-i)+j}`])
}
}
boardValues.n15 = "maually set"
console.log("n15", boardValues.n15)
console.log(Object.keys(boardValues).sort((a, b) => Number(a.slice(1)) - Number(b.slice(1)))) //sorted values
return boardValues
}
n = 7
boardValues = generateBoardValues(n)
board = generateBoard(n, "white")
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<p [innerHTML]="boardValues.n12"></p> <!--Works-->
<div [innerHTML]="board | safeHTML"> <!-- displays table but not desired cell contents-->
This approche is very expensive. I wouldn't use innerHTML in your case. You should handle this in your template file and use *ngFor.

Populate html table with javascript array

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';
}

How to add nested table to datatable?

I need to add a nested table to each row of a jquery datatable(using legacy datatables). So, I tried using example from datatables.net for child rows and modifying it to my needs as I need for the child rows to show at all times, rather than on clicking the parent row.Here is the code I am using both to build my inner table and then display it..
function buildInnerTable(){
var keys = Object.keys(reportApp.gridData),
len = keys.length,
j = 0,
prop,
value;
while (j < len) {
prop = keys[j];
value = reportApp.gridData[prop];
detLen = value.detail.length;
var rowVals = [];
for(var i = 0; i < detLen; i++){
tmpRow = "<tr><td>"+value.detail[i].invtid+"</td>"+
"<td>"+value.detail[i].bf+"</td>"+
"<td>"+value.detail[i].qtyship+"</td>"+
"<td>"+value.detail[i].ordqty+"</td>"+
"<td>"+value.detail[i].bf+"</td>"+
"<td>"+value.detail[i].exttreating+"</td>"+
"<td>"+value.detail[i].extpriceinvc+"</td>"+
"<td>"+value.detail[i].misc+"</td>"+
"<td>"+value.detail[i].extother+"</td>"+
"<td>"+value.detail[i].calcext+"</td></tr>";
rowVals.push(tmpRow);
}
setTableRow(rowVals , j);
j += 1;
}
function setTableRow(rowVals , ndx){
$("#gridTbl > tbody > tr:eq("+ ndx+ ")").after("<table><tr><th>InvtID</th>"+
"<th>Clss</th><th>Pieces</th><th>BilQty</th><th>BF</th><th>Treating</th>"+
"<th>Wood</th><th>NEED NAME</th><th>Other</th><th>Misc</th><th>Total</th></tr>"+
rowVals);
But, I am not getting what I need to get. What it looks like is that the datatables adds a new row and then sets the new table inside the first cell on new row. However, when I view source, that isn't what is happening at all. It closes the previous row and then inserts new table...
I am attaching a screenshot. What I need is for the details to show below the main item rows and to be aligned in same way. Any help in where I am wrong will be greatly appreciated.
Ok... Finally figured this out.
In order to make the view show normally, I had to add a new row to the datatable and then, in side that row, add my new table. However, this caused an indexing issue with the table. So, I had to check the index each time before I added new row. I am posting working code in the hope that it will help someone else.
function buildInnerTable(){
var keys = Object.keys(reportApp.gridData),
len = keys.length,
j = 0,
prop,
value;
while (j < len) {
prop = keys[j];
value = reportApp.gridData[prop];
detLen = value.detail.length;
var rowVals = [];
//THIS NEXT LINE IS WHERE I GET MY INDEX...
var ndx = ($("tr:contains("+value.invcnbr+ ")").index());
for(var i = 0; i < detLen; i++){
tmpRow = "<tr><td>"+value.detail[i].invtid+"</td>"+
"<td>"+value.detail[i].bf+"</td>"+
"<td>"+value.detail[i].qtyship+"</td>"+
"<td>"+value.detail[i].ordqty+"</td>"+
"<td>"+value.detail[i].bf+"</td>"+
"<td>"+value.detail[i].exttreating+"</td>"+
"<td>"+value.detail[i].extpriceinvc+"</td>"+
"<td>"+value.detail[i].misc+"</td>"+
"<td>"+value.detail[i].extother+"</td>"+
"<td>"+value.detail[i].calcext+"</td></tr>";
rowVals.push(tmpRow);
}
setTableRow(rowVals,ndx);
}
j += 1;
}
}
function setTableRow(rowVals,ndx){
var outerTbl = $('#gridTbl').DataTable();
var tr = $("#gridTbl > tbody > tr:eq("+ ndx+ ")");
//NOTE HOW I ADD A ROW AND THEN ADD NEW TABLE TO CELL IN THE ROW.
var innerTbl = "<tr><td colspan = 10><table style = 'background- color:#FFFFFF; width:100%; border:1px solid;'><tr><td>InvtID</td>"+
"<td>Clss</td><td>Pieces</td><td>BilQty</td><td>BF</td><td>Treating</td>"+
"<td>Wood</td><td>NEED NAME</td><td>Other</td><td>Misc</td><td>Total</td></tr>"+
rowVals + "</td></tr>";
tr.after(innerTbl).show();
}

Separate rows and columns while creating 2d dynamic table

I can't separate row and column td's as I create a 2d table with jquery..
How do I create 10 rows 10 columns 2d table:
what I have done so far:
$(document).ready(function () {
for (var i = 1; i <= 10; i++) {
$('.box').append('<td/>' + '</p>');
for (var j = 1; j <= 10; j++); {
$('.box').append('<td/>');
}
}
});
http://jsfiddle.net/VS37n/
thnx in advance!
You want a table that has 10 columns and 10 rows.
var rows = 10;
var cols = 10;
In an HTML table structure, rows come first in the hierarchy, so, create those first:
$(document).ready(function() {
var rows = 10;
var cols = 10;
var box = $('.box');
for (var r = 0; r < rows; r++) {
var tr = $('<tr>');
//Here we will append the columns to the row before appending it to the box.
box.append(tr);
}
});
The above code only makes 10 rows for us. Now we need to add 10 columns to each row:
$(document).ready(function() {
var rows = 10;
var cols = 10;
var box = $('.box');
for (var r = 0; r < rows; r++) {
var tr = $('<tr>');
for (var c = 0; c < cols; c++) {
tr.append($('<td><p></p></td>')); //Create the table cell, with a p element as in your example, and append it to the row.
}
box.append(tr);
}
});
See this FIDDLE
UPDATE
I just noticed that the jQuery selector from your post selects the <div> element with class .box. You want to add these rows and columns, however, to a <table> element, which doesn't exist. I'd suggest you add a <table> element into your HTML, or, add it with Javascript before adding the rows.
If you can add a <table> element inside of your .box div, then you would just change the following line:
var box = $('.box');
to:
var box = $('.box table:first');
If you can't change the HTML for some reason, then you can dynamically create the table before the rows and columns:
var box = $('<table>').appendTo('.box');
Is this what you're trying to do?
$(document).ready(function () {
var tdHtml = "":
var trHtml = "";
var tableHtml = "";
for(var i=1;i<=10;i++)
{
tdHtml += "<td></td>";
}
for(var j=1;j<=10;j++);
{
trHtml += ("<tr>" + tdHtml + "</tr>");
}
tableHtml = ("<table>" + trHtml + "</table>");
$('.box').innerHtml(tableHtml);
});
You had a ; after your for loop :
for (var j = 1; j <= 10; j++); {
$('.box').append('<td/>');
}
Furthermore, you are not adding <tr> elements.
See the updated fiddle

Create HTML table from javascript array

I want to get all classes of the HTML element on my page, split it and store it in array. After that I want to write it into my table in the div with the id "table" which I already have.
So far I have this code:
var string = $('html').attr('class');
var array = string.split(' ');
var arrayLength = parseInt(array.length);
for (i=0; i<=arrayLength; i++) {
// code
}
<div id="test><!-- table goes here --></div>
Can you help me with the rest?
btw, the HTML element has the classes from a modernizr.js.
PS: The code is combination of pure JS and jQuery. Because I dont know how to get all classes of the HTML element in pure JS. Any Idea?
If you're trying to remove jQuery altogether use this:
// Get array of classes without jQuery
var array = document.getElementsByTagName('html')[0].className.split(/\s+/);
var arrayLength = array.length;
var theTable = document.createElement('table');
// Note, don't forget the var keyword!
for (var i = 0, tr, td; i < arrayLength; i++) {
tr = document.createElement('tr');
td = document.createElement('td');
td.appendChild(document.createTextNode(array[i]));
tr.appendChild(td);
theTable.appendChild(tr);
}
document.getElementById('table').appendChild(theTable);
if you have a table already in the html
<div id="test><table >
</table>
</div>
you can simply append new rows to it,
var string = $('html').attr('class');
var array = string.split(' ');
var arrayLength = parseInt(array.length);
for (i=0; i<=arrayLength; i++) {
$("#test table") .append('<tr><td>'+array[i]+'</td></tr>')
}
It is not clear if you want the class names per row or per column. These examples are one class name per row. Try this:
var elm = $('#test'),
table = $('<table>').appendTo(elm);
$(document.documentElement.className.split(' ').each(function() {
table.append('<tr><td>'+this+'</td></tr>');
});
I used native code to get the classNames of the HTML element: document.documentElement.className, but you might as well use $('html').attr('class').
A native JS example using innerHTML:
var d = window.document,
elm = d.getElementById('test'),
html = '<table>',
classes = d.documentElement.classNames.split(' '),
i = 0;
for(; classes[i]; i++) {
html += '<tr><td>' + classes[i] + '</td></tr>';
}
elm.innerHTML = html + '</table>;

Categories