I am building a table with JQuery and everything seems to work, except I can't get the header to show up. I'm declaring the header, appending to the table, then appending the column names to the header. The rest of the table displays exactly how I want it to. I didn't think it should matter what order I do this in. What am I doing wrong?
$(document).ready(function(){
if ($('[attr="searchResultsJson"]').length)
{
$('.comment-section').hide();
$('#InboxDetailsDrawer').hide();
$('.approval-outer-wrap').prepend(drawTable());
}
});
function drawTable(){
var table = $('<table id="search-results" />');
var header = $('<thead />');
table.append(header);
header.append = $('<tr><th>First Name</th><th>Last Name</th><th>Date of Birth</th><th>Data Pulse ID</th><th>Laserfiche ID</th></tr>');
var body = $('<tbody />');
table.append(body);
var json = $('[attr="searchResultsJson"] [type="text"]').text();
console.log(json);
var searchResults = JSON.parse(json);
for (var i = 0; i < searchResults.length; i++)
{
body.append('<tr>'+
`<td>${searchResults[i].patientFirstName}</td>` +
`<td>${searchResults[i].patientLastName}</td>` +
`<td>${searchResults[i].patientDateOfBirth}</td>` +
`<td>${searchResults[i].patientDataPulseID}</td>` +
`<td>${searchResults[i].patientLaserFicheID}</td>` +
'</tr>')
}
return table;
}
The append() is a function and you need to pass the content as an argument against append = when appending the header content. Please find the corrected code below.
$(document).ready(drawTable);
function drawTable() {
var table = $('<table id="search-results">');
var header = $('<thead>');
table.append(header);
header.append('<tr><th>First Name</th><th>Last Name</th><th>Date of Birth</th><th>Data Pulse ID</th><th>Laserfiche ID</th></tr>');
var body = $('<tbody>');
table.append(body);
$('body').append(table);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Related
I'm trying to write some simple Javascript that uses the Trello API to get all boards / lists / cards from my account and add them into an sortable table (using the Datatables jquery plugin).
I've so far managed to write a jsfiddle that gets all this information and writes it to a page, but I can't work out how to store all this information into some sort of data structure that can then be passed to the datatable plugin.
This is the fiddle I have so far that gets the data from Trello:
JS Fiddle Link
var carddata = [];
Trello.members.get("me", function(member) {
$("#fullName").text(member.fullName);
var boardUrl = "";
boardUrl = "members/me/boards";
Trello.get(boardUrl, function(boards) {
$.each(boards, function(ix, board) {
Trello.get("/boards/" + board.id + "/lists", function(lists) {
$.each(lists, function(ix, list) {
Trello.get("lists/" + list.id + "/cards", function(cards) {
$.each(cards, function(ix, card) {
console.log("boardname: " + board.name + "; list name: " + list.name + "; card name: " + card.name);
carddata.push(
"boardname: " + board.name +
"; list name: " + list.name +
"; card name: " + card.name
);
var $tablerow = "";
$tablerow = $(
"<tr><td>" + board.name +
"</td><td>" + list.name +
"</td><td>" + card.name +
"</td></tr>"
).appendTo("#table_body");
});
/*
for (i = 0; i < carddata.length; i++) {
console.log("carddata: " + carddata[i]);
}
*/
});
});
});
});
});
});
// **** carddata array is empty at this point ****
for (i = 0; i < carddata.length; i++) {
console.log("carddata: " + carddata[i]);
}
It loops through all boards, lists and cards and currently adds what it finds to a html table (and also an array). I then use the Datatables plugin to change that HTML table into a sortable table.
However the plugin is seeing the HTML table as empty (from what I can see), I presume this is because of something like the plugin code being called before the Javascript builds up the table in HTML.
So instead I planned to add all the data into an array, and then pass that array into the datatable as a datasource, but I can 't see how to make the array accessible outside the very inner loop. From doing some searches I think this is to do with closures and scope but I'm struggling to understand how they work (I'm very new to Javascript).
Is anyone able to help me get this basic code working and show me what I'm doing wrong?
Thanks,
David.
The following code snippet demonstrate how to add data to data table after table created. For how to wait for all asyn requests completed, setTimeout is used to simulate Trello.get method for the asyn behavior.
var boardHash = {};
var listHash = {};
var updateLoggedIn = function() {
$("#loggedout").toggle(!isLoggedIn);
$("#loggedin").toggle(isLoggedIn);
};
var loadCardData = function(){
var carddata = [];
var loadMember = function() {
setTimeout(function(){
console.log("Member loaded");
loadBoard();
},2000);
}
var loadBoard = function() {
setTimeout(function(){
console.log("Boards loaded");
var listPromises = [];
loadList(["boardA","boardB","boardC"],listPromises);
$.when.apply($, listPromises).then(function(){
table.rows.add(carddata).draw("");
});
},1000);
};
var loadList = function(boards,listPromises){
$.each(boards,function(boardIndex, boardValue){
var listDefered = $.Deferred();
listPromises.push(listDefered.promise());
setTimeout(function(){
console.log(boardValue+" lists loaded");
var cardPromises = [];
loadCard(["listA","listA","listC"],boardValue,cardPromises);
$.when.apply($, cardPromises).then(function(){
listDefered.resolve();
});
},(boardIndex+1)*900);
});
};
var loadCard = function(lists,boardValue,cardPromises){
$.each(["listA","listA","listC"],function(listIndex, listValue){
var cardDefered = $.Deferred();
cardPromises.push(cardDefered.promise());
setTimeout(function(){
console.log(boardValue+" "+listValue+" cards loaded");
$.each(["cardA","cardB","cardC"],function(cardIndex, cardValue){
carddata.push({
"boardName":boardValue,
"listName":listValue,
"cardName":cardValue
});
});
cardDefered.resolve();
},(listIndex+1)*800);
});
};
loadMember();
};
var logout = function() {
updateLoggedIn();
};
$("#connectLink")
.click(function() {
loadCardData();
});
$("#disconnect").click(logout);
var consoleLine = "<p class=\"console-line\"></p>";
console = {
log: function(text) {
$("#console-log").append($(consoleLine).html(text));
}
};
var table = null;
$(document).ready( function () {
table = $('#table_id').DataTable({
columns: [
{ data: 'boardName' },
{ data: 'listName' },
{ data: 'cardName' }
]
});
} );
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<link href="//cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css" rel="stylesheet" />
<script src="//cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<div id="loggedout">
<a id="connectLink" href="#">Connect To Trello</a>
</div>
</head>
<div id="loggedin">
<div id="header">
Logged in to as <span id="fullName"></span>
<a id="disconnect" href="#">Log Out</a>
</div>
<div id="output"></div>
</div>
<table id="table_id" class="display" border=1>
<thead>
<tr>
<th>Board</th>
<th>List</th>
<th>Card</th>
</tr>
</thead>
<tbody id="table_body">
</tbody>
</table>
<div id="console-log"></div>
</html>
For adding data to data table
So in your code, add the columns options to the data table, and use rows.add method to add data to data table when all ajax request are done.
Wait for all ajax request completed
The most tricky part is how to ensure all response are done, this can be achieved by $.Deferred() and $.when.apply, see JQuery document and What does $.when.apply($, someArray) do? for more details.
My code is working fine but I can't print table that I made from JSON values. Any suggestions??
var resData = {"key1":"value","key2":"value"};
var table = $('<html/>').append('<thead><tr><th>Filter</th><th>Values</th></tr></thead>').appendTo('body'),
tbody = table.append('<tbody/>');
$.each(resData, function(key, value){
tbody.append('<tr><td>'+key+'</td><td>'+value+'</td></tr>');
});
console.log(table);
Simply you can make like this.
var resData = {"key1":"value","key2":"value"};
var table_str = '<table><thead><tr><th>Filter</th><th>Values</th></tr></thead>';
table_str += '<tbody>';
$.each(resData, function(key, value){
table_str +='<tr><td>'+key+'</td><td>'+value+'</td></tr>';
});
$("#content").html(table_str);
console.log(table_str);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="content">
</div>
first create complete table html in var table and then append table to body
You can add a varible and concatinate it with value and then append to html
var resData = {"key1":"value","key2":"value"};
var table='<table><thead><tr><th>Filter</th><th>Values</th></tr></thead><tbody><tbody/>';
$.each(resData, function(key, value){
table+='<tr><td>'+key+'</td><td>'+value+'</td></tr>';
});
table+='</table>';
$('<html/>').append(table);
console.log(table);
You're printing the jQuery object directly to the console. I presume you need the html content of the table. You need to use console.log(table.html()). See the html() docs
Try this in JavaScript:
var resData = {"key1":"value","key2":"value"};
var table = '<table><thead><tr><th>Filter</th><th>Values</th></tr></thead>';
table += '<tbody>';
for (var i in resData) {
table += '<tr><td>'+i+'</td><td>'+resData[i]+'</td></tr>';
}
document.getElementById("table").innerHTML = table;
table,th,td { border: 1px solid black; }
<div id="table">
</div>
actually i am making a todolist so i want to replace div which i added through in innerhtml with tr and after created of the first row in html please check
Html Part:
<table id="ws-table" class="table table-bordered">
<tr id="insert">
<th>#</th>
<th>Date</th>
<th>Items</th>
<th>Edit / Delete</th>
</tr>
<!-- Here i wanted an tr
</table>
actually i am making a todolist so i want to replace div which i added through in innerhtml with tr and after created of the first row in html please check
javascript part :
var takeInput;
var DATA = [];
load();
function insertItem(){
takeInput = document.getElementById('item').value;
DATA.push(takeInput);
renderJson(DATA);
document.getElementById('item').value = "";
}
function renderJson(data){
document.getElementById('container').innerHTML = "";
for(var i in data){
container.innerHTML = container.innerHTML + "<div id=" + i + " onclick='removeItem(this.id)'><input type='checkbox'/><label>"+data[i]+"</label></div>";
}
save();
}
function removeItem(Id){
var itemId = document.getElementById(Id);
if(itemId.childNodes[0].checked == true){
var arr_ind = DATA.indexOf(itemId.childNodes[1].innerText);
DATA.splice(arr_ind,1);
itemId.parentNode.removeChild(itemId);
save();
}
}
function save(){
localStorage.myList = JSON.stringify(DATA);
}
function load(){
DATA = JSON.parse(localStorage.myList);
renderJson(DATA);
}
Element.innerHTML is for replacement only, so you need to read it first concatenate with new row and then assing back, better use Element.insertAdjacentHTML():
var row = "<tr><td>1</td><td>2</td><td>3</td><td>4</td></tr>";
document.querySelector("#ws-table tbody").insertAdjacentHTML("beforeend", row);
You may want to use thead for your table header. Check this thread for more information.
I am working on javascript.
I have some API calls(Using Ajax) in my code.
There is a button in my UI
on click of this button I am making some API call using AJAX and displaying below HTML UI:
In the table above there are 2 rows. Now if I close this popup and then again click on User Dashboard button it will append those 2 rows again in the table. I dont want to append those rows again.
My code to form table using AJAX response looks like below:
getUserAccountDetailsCallback : function(userid, appid, response){
if(response != "")
{
var res = JSON.parse(response);
var totalNoOfApps = document.getElementById('totalSites');
var totalNoOfSubscriptions = document.getElementById('totalSubscribers');
totalNoOfApps.innerHTML = res.totalNoOfApps;
totalNoOfSubscriptions.innerHTML = res.totalNoOfSubscriptions;
if(res.subscriptionsForCurrentAppId.length > 0){
for(var i = 0; i < res.subscriptionsForCurrentAppId.length; i++){
var td1=document.createElement('td');
td1.style.width = '30';
td1.innerHTML=i+1;
var td2=document.createElement('td');
td2.innerHTML=res.subscriptionsForCurrentAppId[i].gatewayName;
var td3=document.createElement('td');
td3.innerHTML=res.subscriptionsForCurrentAppId[i].priceCurrencyIso;
var td4=document.createElement('td');
td4.innerHTML=res.subscriptionsForCurrentAppId[i].amountPaid;
var date = new Date(res.subscriptionsForCurrentAppId[i].subscribedDate);
date.toString();
var td5=document.createElement('td');
td5.innerHTML=date.getMonth()+1 + '/' +date.getDate() + '/' + date.getFullYear();//res.subscriptionsForCurrentAppId[i].subscribedDate;
var td6=document.createElement('td');
td6.innerHTML=res.subscriptionsForCurrentAppId[i].transactionId;
var td7=document.createElement('td');
td7.innerHTML=res.subscriptionsForCurrentAppId[i].active;
var tr=document.createElement('tr');
tr.appendChild(td1);
tr.appendChild(td2);
tr.appendChild(td3);
tr.appendChild(td4);
tr.appendChild(td5);
tr.appendChild(td6);
tr.appendChild(td7);
var table = document.getElementById('tbl');
table.appendChild(tr);
}
}
}
}
Please help. Where I am doing wrong.
add thead and tbody
<table>
<thead><tr><th>#</th><th>Gateway.....</tr></thead>
<tbody id="tBodyId"></tbody>
</table>
remove the content of tbody before appending
like this:
var tBody = document.getElementById("tBodyID");
while (tBody.firstChild) {
tBody.removeChild(tBody.firstChild);
}
if(res.subscriptionsForCurrentAppId.length > 0){
So I have set up two javascript arrays to pull information from some php. One array gets the name of the category to be clicked on, while the other array stores the class and id tag for the category. The class and id tags are the same other than there css type, but the array needs to output them into document elements and then, when clicked, affect the relevant areas of the document. I also need to remove duplicates from the arrays, which doesn't seem to work under my current code:
<script type="text/javascript">
var BookSeries = [];
var BookClass = [];
var i=0;
</script>
then variables for the array are pulled from php and output this way:
<script type="text/javascript">
var uniqueSeries = BookSeries.filter(function(elem, pos) {
return BookSeries.indexOf(elem) == pos;
});
var uniqueClass = BookClass.filter(function(elem, pos) {
return BookClass.indexOf(elem) == pos;
});
while (uniqueSeries[i]) {
document.write( "<span id='"+uniqueClass[i]+"'>"+uniqueSeries[i]+"</span>" );
i++;
}
for(var i = 0; i < uniqueClass.length; i++) {
$np("#"+uniqueClass[i]).click(function(){
$np(".postitem").fadeOut(200);
$np("."+uniqueClass[i]).fadeIn(200);
});
}
</script>
You are using jquery so you can do the following for appending the elements to the DOM:
var htmlString = "";
for (var i = 0; i < uniqueSeries.length; i++) {
htmlString += "<span id='"+uniqueClass[i]+"'>"+uniqueSeries[i]+"</span>";
}
$("#myContainer").html(htmlString);
Not sure what is $np so I'll assume you meant jquery's $.
for(var i = 0; i < uniqueClass.length; i++) {
var uClass = uniqueClass[i];
$("#" + uClass).click(function(){
$(".postitem").fadeOut(200);
$("." + uClass).fadeIn(200);
});
}
Edit:
"#myContainer" refers to the id of the dom element you want to append the html to. if you just want to append it to document you can do:
$(document).appendTo(htmlString);
Also see I updated the code above to reflect your comments about the uniqueClass array.