How to add header for dynamic table - javascript

Hello everybody I am drawing dynamic table and I want to add header for table how to add header to dynamic table here is my table code:
$.get('http://myDomain.com/RIA/topIndiaDetails.asp', function(data)
{
console.log("####"+data);
var up = new Image();
var down = new Image();
up.src = "../../jquery.mobile/images/up.png";
down.src = "../../jquery.mobile/images/down.png"
substr = data.split('$');
//alert(substr.length);
//var theader = '<table border="1">\n';
//<table id="auditOverview" border="1">
var theader = '<table border="1" id=\"tableId\">\n';
var tbody = '';
for (var out = 1;out<substr.length-1;out++)
{
//alert(substr[out]);
tbody += '<tr>';
var pra = substr[out].split('|^');
//alert('pra.length is: '+pra.length);
for (var i=0;i<pra.length-1;i++)
{
tbody += '<td>';
if (pra[i]=="Red")
{
pra[i].append("<img id='theImg' src='../../jquery.mobile/images/down.png'/>");
}
else if (pra[i]=="Green")
{
pra[i].append("<img id='theImg' src='../../jquery.mobile/images/up.png'/>");
}
tbody += pra[i];
tbody += '</td>'
}
tbody += '</tr>\n';
}
var tfooter = '</table>';
document.getElementById('wrapper').innerHTML = theader + tbody + tfooter;
});
Any help will be appreciated. Thanks in advance.

You can build your header:
var header = "<th>...</th>";
Then:
$("table").append(header);

if I could get your point correctly
DEMO: http://jsfiddle.net/75zFX/8/
var colheader = '<tr><th>Column1</th><th>Column2</th> .....</tr>\n';
var tbody = colheader ;// and replace with var tbody = '';

If u want to add Header Manually to a Table,use this code.
JSP
<th id="example"></th>
JavaScript
$("#example").html("Header Value");

Related

Populating HTML table with Google Sheet data (rows & columns)

Having issues with what it might be a rather easy fix.
Context: My code is currently pulling data from Google Sheets, crafting some sort of table and sending it back to HTML where it repopulates an already existing table.
Issue: I am unable to make it so that it builds columns as well as rows. It pastes the data back all in one go (see image for context).
Files: GS & HTML. I believe the issue is on how I'm crafting the table. I know the current disposition of '' doesn't make sense, bu
HTML table with Gsheet values:
Original Gsheet table:
Google Script
function populateStratTb2(){
var tablerows = SpreadsheetApp.getActive().getSheetByName('supp_str').getRange(1, 5, 1000).getValue();
var tablevalues = SpreadsheetApp.getActive().getSheetByName('supp_str').getRange(4, 1, tablerows).getValues();
var tvlen = tablevalues.length
var active = SpreadsheetApp.getActive();
var sheet = active.getSheetByName("supp_str");
var myRange = sheet.getRange("d3:m" + tvlen);
var data = myRange.getValues();
var optionsHTML = "";
for ( var r = 0; r < 10; r+=1) {
for (var i = 0; i < data.length; i+=1) {
optionsHTML += '<tr><td>' + data[i][r] + '</td></tr>';
}};
return optionsHTML;
}
HTML Script
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(function(){
google.script.run
.withSuccessHandler(displayData)
.populateStratTb2();
});
function displayData(hl){
document.getElementById('strattable').innerHTML=hl;
}
console.log('MyCode');
</script>
PS. I have spent a good couple hours scrolling though the forum picking bits and improving my original code. I am sure this question (or similar) has been answered already but I can't manage to find it.
In your script, how about the following modifications?
Modification 1:
If your for loop is used, how about the following modification?
function populateStratTb2() {
var sheet = SpreadsheetApp.getActive().getSheetByName('supp_str');
var tablerows = sheet.getRange(1, 5, 1000).getValue();
var tablevalues = sheet.getRange(4, 1, tablerows).getValues();
var tvlen = tablevalues.length
var myRange = sheet.getRange("d3:m" + tvlen);
var data = myRange.getValues();
var optionsHTML = "";
for (var r = 0; r < 10; r += 1) {
var row = "";
for (var i = 0; i < data.length; i += 1) {
row += '<td>' + data[i][r] + '</td>';
}
optionsHTML += '<tr>' + row + '</tr>';
}
optionsHTML = '<table border="1" style="border-collapse: collapse">' + optionsHTML + "</table>";
return optionsHTML;
}
I'm worried that your for loop might not be your expected result. So, I would like to proposed one more modified script as "Modification 2".
Modification 2:
If your data is converted to the HTML table, how about the following modification?
function populateStratTb2() {
var sheet = SpreadsheetApp.getActive().getSheetByName('supp_str');
var tablerows = sheet.getRange(1, 5, 1000).getValue();
var tablevalues = sheet.getRange(4, 1, tablerows).getValues();
var tvlen = tablevalues.length
var myRange = sheet.getRange("d3:m" + tvlen);
var data = myRange.getValues();
var optionsHTML = '<table border="1" style="border-collapse: collapse">' + data.reduce((s, r) => s += "<tr>" + r.map(c => `<td>${c}</td>`).join("") + "</tr>", "") + "</table>";
return optionsHTML;
}
Note:
If you don't want to add the border, please modify <table border="1" style="border-collapse: collapse"> to <table>.
From your reply, I added 2 sample scripts for the script for obtaining the same result from reduce and for loop as follows.
reduce
var optionsHTML = '<table border="1" style="border-collapse: collapse">' + data.reduce((s, r) => s += "<tr>" + r.map(c => `<td>${c}</td>`).join("") + "</tr>", "") + "</table>";
for loop
var optionsHTML = "";
for (var r = 0; r < data.length; r++) {
var row = "";
for (var c = 0; c < data[r].length; c++) {
row += '<td>' + data[r][c] + '</td>';
}
optionsHTML += '<tr>' + row + '</tr>';
}
optionsHTML = '<table border="1" style="border-collapse: collapse">' + optionsHTML + "</table>";
Reference:
reduce()

How do I include a header in a generated table of my javascript?

I receive in my javascript a json data that it is converted to a html table.
The script is working.. but how do I include a header in my table?
Here is the code:
<script>
$(document).ready(function(){
$('#id_adv').DataTable();
$('#id_adv').on('click','.btn',function(){
var currow = $(this).closest('tr');
var result = currow.find('td:eq(1)').text();
$.get('{% url "prop_table" %}', {var1:result}, function (data_prop) {
var data = data_prop['data_prop']
var data_json = JSON.parse(data);
var html = "";
for (var i = 0; i < data_json.length; i++) {
html += "<tr><td>" + data_json[i].fields.var1 + "</td><td>" + data_json[i].fields.var2 + "</td><tr>";
}
$('#id_prop').html(html);
})
document.getElementById('total').innerHTML = result;
});
});
</script>
Slight modification to your existing code to add a header. (I've cut out your usage of eval and just kept in the relevant part to create the HTML table header)
<script>
....
var html = "";
html += "<tr><th>Header 1</th><th>Header 2</th><tr>";
for (var i = 0; i < data_json.length; i++) {
html += "<tr><td>" + data_json[i].fields.var1 + "</td><td>" + data_json[i].fields.var2 + "</td><tr>";
}
$('#id_prop').html(html);
....
</script>
This should add a header to your table.
And I agree with the comment in your question, use the built in JSON parsing. eval is just asking to be exploited.
I think that you can add the header after create the table. The createTHead() method creates an empty element and adds it to the table. I.e.:
<script>
function createHeader() {
var table = document.getElementById("myTable");
var header = table.createTHead();
var row = header.insertRow(0);
var cell = row.insertCell(0);
cell.innerHTML = "<b>This is a table header</b>";
}
</script>

Parse ASCII as plain text exporting to Excel from js

Having a bit of trouble when exporting a spreadsheet. The tool is to create tracking links, everything works fine except when the link contains ascii characters. For example, someurl.com&trackingparameter%3d.
When this happens, it all works within the app, but when exported to the spreadsheet it would read as someurl.com&trackingparameter=.
Wondering how I can parse these ascii characters as plain text on the export. Thanks in advance for any assistance.
Best,
Erik
<script>
$(document).ready(function() {
$("#btnExport").click(function(e) {
e.preventDefault();
var data_type = 'data:application/vnd.ms-excel';
var table_div = document.getElementById('wrapper');
var table_html = table_div.outerHTML.replace(/ /g, '%20');
var a = document.createElement('a');
a.href = data_type + ', ' + table_html;
a.download = 'exported_URLS_' + Math.floor((Math.random() * 9999999) + 1000000) + '.xls';
a.click();
});
});
</script>
<script type="text/javascript">
function createTable() {
var deletebutton = '<button class="delete uk-button uk-button-danger" id="delete">delete</button>';
var tbody = '';
var descripdata = '';
var simpleURLdata = '';
var description = document.getElementById('description').value;
var simpleURL = document.getElementById('simpleURL').value;
var baseURL = document.getElementById('baseURL').value;
var s1 = document.getElementById('s1').value;
var s2 = document.getElementById('s2').value;
var s3 = document.getElementById('s3').value;
var s4 = document.getElementById('s4').value;
var ts = document.getElementById('ts').value;
var hdr = document.getElementById('hdr').value;
var hdrid = document.getElementById('hdrid').value;
var dmhdr = document.getElementById('dmhdr').value;
var utm_source = document.getElementById('utm_source').value;
var utm_medium = document.getElementById('utm_medium').value;
var utm_campaign = document.getElementById('utm_campaign').value;
var utm_category = document.getElementById('utm_category').value;
tbody += '<td>';
tbody += baseURL;
if (s1 != '') {
tbody += '&s1=';
tbody += s1;
}
if (s2 != '') {
tbody += '&s2=';
tbody += s2;
}
if (s3 != '') {
tbody += '&s3=';
tbody += s3;
}
if (s4 != '') {
tbody += '&s4=';
tbody += s4;
}
if (ts != '') {
tbody += '&ts=';
tbody += ts;
}
if (hdr != '') {
tbody += '&hdr='
tbody += hdr;
}
if (dmhdr != '') {
tbody += '&dmhdr=';
tbody += dmhdr;
}
if (hdrid != '') {
tbody += '&hdrid=';
tbody += hdrid;
}
if (utm_source != '') {
tbody += '&utm_source=';
tbody += utm_source;
}
if (utm_medium != '') {
tbody += '&utm_medium=';
tbody += utm_medium;
}
if (utm_campaign != '') {
tbody += '&utm_campaign=';
tbody += utm_campaign;
}
if (utm_category != '') {
tbody += '&utm_category=';
tbody += utm_category;
}
tbody += '</td>';
descripdata += '<td>';
if (description != '') {
descripdata += description;
}
descripdata += '</td>';
simpleURLdata += '<td>';
if (simpleURL != '') {
simpleURLdata += simpleURL;
}
simpleURLdata += '</td>';
var table = document.getElementById('urls');
var row = table.insertRow(0);
var cell1 = row.insertCell(0);
cell1.innerHTML = tbody;
var cell2 = row.insertCell(1);
cell2.innerHTML = descripdata;
var cell3 = row.insertCell(2);
cell3.innerHTML = simpleURLdata;
var cell4 = row.insertCell(3);
cell4.innerHTML = deletebutton;
}
</script>
You can use javascript native functions escape(), encodeURI() or encodeURIComponent() if you want to retain %3d as %3d.
Further help regarding these can be found at When are you supposed to use escape instead of encodeURI / encodeURIComponent?

Dynamically creating an html table with Javascript

I am trying to create a table based on user input (actually two or three tables depending on the user input..) using Javascript, I am very much native to PHP and have already got this working in PHP, however i would like the user to be able to see the table before the query it. I found a script on here that partially did what I wanted and have attempted to edit it (I found it surprisingly similar to PHP) Basically it calculates the total amount of cells (ports) splits it by rows and columns, the "super" column is used if the user would like it to be split into multiple tables, which align next to each other, hence the div tag. Here's my JS:
<html>
<head>
<script type="text/javascript">
function createTable()
{
var num_ports = document.getElementById('ports').value;
var num_super = document.getElementById('super').value;
var num_rows = document.getElementById('rows').value;
var num_cols = document.getElementById('cols').value;
var tbody = '';
var colStart = num_cols / num_super;
for( var i=0; i<num_super; i++){
var theader = '<div><table border="1">\n';
for(u=1; u<=num_row; u++){
tbody += '<tr>';
for( var j=0; j<colStart; j++)
{
tbody += '<td>';
tbody += 'Cell ' + i + ',' + j;
tbody += '</td>'
}
tbody += '</tr>\n';
}
var tfooter = '</table></div>';
document.getElementById('wrapper').innerHTML = theader + tbody + tfooter;
}
</script>
</head>
<body>
<form name="tablegen">
<label>Ports: <input type="text" name="ports" id="ports"/></label><br />
<label>Super Columns: <input type="text" name="super" id="super"/></label><br />
<label>Rows: <input type="text" name="rows" id="rows"/></label><br />
<label>Columns: <input type="text" name="cols" id="cols"/></label><br/>
<input name="generate" type="button" value="Create Table!" onclick='createTable();'/>
</form>
<div id="wrapper"></div>
</body>
</html>
Here is what the final output looks like after it has been processed by PHP (ports:24, col:6, rows:2, super:2):
Here is a js fiddle that I threw together:
http://jsfiddle.net/9SnLB/
Currently, when I click the button nothing happens, but, I suppose that is my first issue, but am I going about the setup correctly? Why wont the button run the function?
Two mistakes. One you didn't close the function bracket, ie a missing } at the end. The second is you used $row instead of the variable you created num_rows. For some reason it doesn't work in the fiddle, it does however work locally. The fiddle is saying the createTable function is undefined.
function createTable()
{
var num_ports = document.getElementById('ports').value;
var num_super = document.getElementById('super').value;
var num_rows = document.getElementById('rows').value;
var num_cols = document.getElementById('cols').value;
var tbody = '';
var colStart = num_cols / num_super;
for( var i=0; i<num_super; i++){
var theader = '<div><table border="1">\n';
for($u=1; $u<=num_rows; $u++){
tbody += '<tr>';
for( var j=0; j<colStart; j++)
{
tbody += '<td>';
tbody += 'Cell ' + i + ',' + j;
tbody += '</td>'
}
tbody += '</tr>\n';
}
var tfooter = '</table></div>';
document.getElementById('wrapper').innerHTML = theader + tbody + tfooter;
}
}
var table = [["a1","a2","a3"]["b1","b2","b3"]["c1","c2","c3"]];
for(x = table.length;x > 0;x--) {
document.write("<tr>");
for(y = table[x].length;y > 0;y--) {
document.write("<td>"+y+"</td>");
}
document.write("</tr>");
}
Sorry if the syntax is wrong. You get the idea.
You need to change your jsFiddle framework to "no wrap (head)" and correct errors in the javascript. "no wrap (head)" will allow access the function. The "for ($u=1" loop is missing the close brace and $row should be num_rows. The "for (j=0" loop is missing a semicolon at the last "tbody=".
here's the corrected js.
function createTable() {
var num_ports = document.getElementById('ports').value;
var num_super = document.getElementById('super').value;
var num_rows = document.getElementById('rows').value;
var num_cols = document.getElementById('cols').value;
var tbody = '';
var colStart = num_cols / num_super;
for (var i = 0; i < num_super; i++) {
var theader = '<div><table border="1">\n';
for ($u = 1; $u <= num_rows; $u++) {
tbody += '<tr>';
for (var j = 0; j < colStart; j++) {
tbody += '<td>';
tbody += 'Cell ' + i + ',' + j;
tbody += '</td>';
}
}
tbody += '</tr>\n';
}
var tfooter = '</table></div>';
document.getElementById('wrapper').innerHTML = theader + tbody + tfooter;
}

jQuery add <thead> and add <tbody>

How do I add <thead> and <tbody> this using jQuery?
the problem is my table has 1 or 2 th rows?
$('#myTable tr:has(th)').wrap('<thead></thead>');
<table id="myTable">
<tr><th>1</th><th>2</th><th>3</th><th>4</th></tr>
<tr><th>1</th><th>2</th><th>3</th><th>4</th></tr>
<tr><td>1</td><td>2</td><td>3</td><td>4</td></tr>
<tr><td>1</td><td>2</td><td>3</td><td>4</td></tr>
<tr><td>1</td><td>2</td><td>3</td><td>4</td></tr>
<tr><td>1</td><td>2</td><td>3</td><td>4</td></tr>
<tr><td>1</td><td>2</td><td>3</td><td>4</td></tr>
</table>
What you need to do is remove the rows and append them to a thead element
var myTable = jQuery("#myTable");
var thead = myTable.find("thead");
var thRows = myTable.find("tr:has(th)");
if (thead.length===0){ //if there is no thead element, add one.
thead = jQuery("<thead></thead>").appendTo(myTable);
}
var copy = thRows.clone(true).appendTo("thead");
thRows.remove();
jsFiddle exmaple
​
use wrapAll instead of wrap
$('#myTable tr:has(th)').wrapAll('<thead></thead>');​
$("#myTable thead").prependTo("#myTable")
function createTable(data) {
var str = "";
str += '<table><thead>';
str += '<tr><td>Pos</td><td>Ref</td></tr></thead><tbody>';
for (var item in data.recentList) {
str += '<tr>';
for (idata in data.recentList[item]) {
str += '<td>' + data.recentList[item][idata] + '</td>';
}
str += '</tr>';
}
str += '</tbody></table>';
$('body').append(str);
}
Working version that creates a table from an array

Categories