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>
I'm working to a homework and I wrote the frontend in html, css, javascript. Till now when I press a button I get some data from backend and in javascript a parse the response. The response is an array of items. An item is a structure. What I want it's to build dynamically a list of those items. I didn't find on google a way of doing that with javascript. Some hints/help?
What I tried, you can see below, is to append some HTML to an HTML element - it didn't work.
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
source.value = "";
destination.value = "";
var array_rides = JSON.parse(this.responseText).results;
var rides_length = array_rides.length;
for (var i = 0;i < rides_length;i++) {
console.log(array_rides[i][DRIVER]);
console.log(array_rides[i][RIDERS]);
console.log(array_rides[i][SOURCE]);
console.log(array_rides[i][DESTINATION]);
console.log(array_rides[i][START]);
console.log(array_rides[i][SEATS_AVAILABLE]);
console.log(array_rides[i][SEATS_TOTAL]);
my_list.append('<span class="name">{0}</span>'.format(array_rides[i][DRIVER]));
}
}
};
So, I want a list which is dynamically populated.
Something like (table ish):
array_rides[0][DRIVER], array_rides[0][RIDERS], ...
array_rides[1][DRIVER], array_rides[1][RIDERS], ...
...
array_rides[n][DRIVER], array_rides[n][RIDERS], ...
which, of cours, to inherit some css.
I assume a list in the document, like a product table or something.
The easiest way to do this is by just looping through your list and inserting it into a table or something. An example could be this:
function somefunc() {
var table = document.getElementById('my_table');
var array_rides = ['cell1', 'cell2', 'cell3', 'cell4'];
var string;
string = "<table>";
for (var i = 0;i < array_rides.length;i++) {
//add table row
string += "<tr>";
//add all items in tabel cells
//you just have to replace the array_rides[i] with array_rides[i].DRIVER, array_rides[i].RIDERS... and so on
string += "<td>"+array_rides[i]+"</td>";
string += "<td>"+array_rides[i]+"</td>";
string += "<td>"+array_rides[i]+"</td>";
string += "<td>"+array_rides[i]+"</td>";
string += "<td>"+array_rides[i]+"</td>";
string += "<td>"+array_rides[i]+"</td>";
//close table row
string += "</tr>";
}
string += "</table>";
table.innerHTML = string;
}
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
}
th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
tr:nth-child(even) {
background-color: #dddddd;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Testpage</title>
</head>
<body onload="somefunc();">
<div id="my_table"></div>
</body>
</html>
basically what this does is take all the data from the array and append them to a table.
You could add some CSS too to make it look nicer
var array = []; //In this i have 2 items
<div id="content"></div>
In this div id I need to pass the above array elements.
Ho can I do this?
Below is the basic example, how you interact with your DOM with javascript.
var array = [1, 2];
var content = document.getElementById("content");
for(var i=0; i< array.length;i++){
content.innerHTML += i + '--' + array[i] + '<br>';
}
<div id="content">
</div>
Big Note:
You can also use Javascript Templating if you are looking for passing a lot of other data as well to the View
You can use document.getElementById to get the id of the <div> and then insert the array as a string which will convert to the comma separated value:
var array = ['apple','ball']; //In this i have 2 items
document.getElementById('content').innerHTML = array.toString();
<div id="content"></div>
You Looking for Something like this ?
<div class="dummy" style="height: 100px;width: 100px;border: 1px solid black;"></div>
jQuery(document).ready(function(){
var arr = ['1','2'];
jQuery.each( arr, function( i, val ) {
jQuery('.dummy').append(val);
jQuery('.dummy').append("<br>");
});
});
jsfiddle : https://jsfiddle.net/vis143/c1kz0b8o/
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 want to extract data from an html table like
<table>
<tr>
<th> Header1 </th>
<th> Header2 </th>
<th> Header3 </th>
</tr>
<tr>
<td> Value 1,1 </td>
<td> Value 2,1 </td>
<td> Value 3,1 </td>
</tr>
... rows ...
</table>
and get arrays:
an array for the headers
a 2d array for the column values (or an array for each column)
How can I do this using jQuery?
I don't care to serialize it, or put it into a JSON object because I want to use it to render a chart.
related General design question:
at the moment I have something like
1. ajax query returns html table
2. use jQuery to get values from html table
3. render chart
does it make more sense to throw a JSON object back from the ajax query and then render a table and a chart from there?
demo updated http://jsfiddle.net/ish1301/cnsnk/
var header = Array();
$("table tr th").each(function(i, v){
header[i] = $(this).text();
})
alert(header);
var data = Array();
$("table tr").each(function(i, v){
data[i] = Array();
$(this).children('td').each(function(ii, vv){
data[i][ii] = $(this).text();
});
})
alert(data);
Something like this?
$(function() {
var headers = $("span",$("#tblVersions")).map(function() {
return this.innerHTML;
}).get();
var rows = $("tbody tr",$("#tblVersions")).map(function() {
return [$("td:eq(0) input:checkbox:checked",this).map(function() {
return this.innerHTML;
}).get()];
}).get();
alert(rows);
});
yet another way of doing it
var headers = jQuery('th').map(function(i,e) { return e.innerHTML;}).get();
var datas = []
jQuery.each(jQuery('tr:gt(0)'), function(i,e ) {
datas.push(jQuery('td', e).map(function(i,e) {
return e.innerHTML;
}).get()
);
});
Something along the lines of:
var thArray = new Array();
var contentArray = new Array();
$('th').each(function(index) {
thArray[index] = $(this).html();
})
$('tr').each(function(indexParent) {
contentArray['row'+indexParent] = new Array();
$(this).children().each(function(indexChild) {
contentArray['row'+indexParent]['col'+indexChild] = $(this).html();
});
});
This gives you two arrays, thArray which is an array of your headings and contentArray which is a 2d array containing rows and columns: contentArray['row1']['col0'] returns " Value 1,1"
Actually, contentArray contains the th's as well... referenced 'row0'
does it make more sense to throw a JSON object back from the ajax query and then render a table and a chart from there?
Yes, absolutely. Return JSON in response to your AJAX request, then you can render the table using something like jQuery Templates and use the same underlying data to generate your chart as well.
Here's a modification of Jerome Wagner's answer that uses recursive maps instead of a map inside an 'each':
http://jsbin.com/oveva3/383/edit
var headers = $("th",$("#meme")).map(function() {
return this.innerHTML;
}).get();
var rows = $("tbody tr",$("#meme")).map(function() {
return [$("td",this).map(function() {
return this.innerHTML;
}).get()];
}).get();
I'm tinkering with the same thing over here, but I prefer iterating through all tables and writing the header and body arrays into properties of each table, so here's my modification to the original answer:
$(function() {
$("table").each(function(){
var $table = $(this),
$headerCells = $("thead th", $(this)),
$rows = $("tbody tr", $(this));
var headers = [],
rows = [];
$headerCells.each(function(k,v) {
headers[headers.length] = $(this).text();
$table.prop("headAry", headers);
});
$rows.each(function(row,v) {
$(this).find("td").each(function(cell,v) {
if (typeof rows[cell] === 'undefined') rows[cell] = [];
rows[cell][row] = $(this).text();
$table.prop("bodAry", rows);
});
});
console.log($(this).prop('headAry'));
console.log($(this).prop('bodAry'));
});
});
JSbin
Use this line of code:
var arrays = [];
$('table').eq(0).find('tr').each((r,row) => arrays.push($(row).find('td,th').map((c,cell) => $(cell).text()).toArray()))
I would think it would make more sense to get a json array back from the ajax call and generate your table/chart from that. With jquery templates this isn't hard at all.