Add Caption and Thead using javascript - javascript

I have made an html table with java script but not understanding how to add the caption and the thead.
var arr =[
["Period Ends", "Payroll Due", "Payday"],
["06/13/15", "06/19/15", "06/26/15"],
];
var body, tab, th, tr, td, tn, row, col;
body = document.getElementsByTagName('body')[0];
tab = document.createElement('table');
for (row=0; row < arr.length; row++){
tr = document.createElement('tr');
for (col=0; col < arr[row].length; col++){
td = document.createElement('td');
tn = document.createTextNode(arr[row][col]);
td.appendChild(tn);
tr.appendChild(td);
}
tab.appendChild(tr);
}
body.appendChild(tab);

This is the approach that I would use
var arr =[
["Period Ends", "Payroll Due", "Payday"],
["06/13/15", "06/19/15", "06/26/15"],
];
var body = document.getElementsByTagName('body')[0];
var tab = document.createElement('table');
var cap = tab.createCaption();
var tr, td, col;
// set caption
cap.innerHTML = 'My Table Caption';
// start from first row (skip row headings)
for (var row=1; row < arr.length; row++){
tr = tab.insertRow(row-1);
for (col=0; col < arr[row].length; col++){
td = tr.insertCell(col);
td.innerHTML = arr[row][col];
}
}
// add row headings
var header = tab.createTHead()
var headerRow = header.insertRow(0);
for (col=0; col < arr[0].length; col++){
td = headerRow.insertCell(col);
td.innerHTML = arr[0][col];
}
body.appendChild(tab);
This makes use of the HTML-spec methods for creating table elements
createCaption
insertRow
createTHead
insertCell
innerHTML
The only quirk I found was that I had to add the tHead after the body rows
Here's a jsfiddle

Related

Set type text inside cell javascript

I want to type text inside the cell but I tried to set attribute with td but it doesn't work. Please help me how can I set attribute to type text in the cell. Thank you for your help!
function addTable() {
rn = window.prompt("Input number of rows", 1);
cn = window.prompt("Input number of columns",1);
var myTableDiv = document.getElementById("myDynamicTable");
var table = document.createElement('TABLE');
table.border = '1';
var tableBody = document.createElement('TBODY');
table.appendChild(tableBody);
for (var i = 0; i < parseInt(rn, 10); i++) {
var tr = document.createElement('TR');
tableBody.appendChild(tr);
for (var j = 0; j < parseInt(cn, 10); j++) {
var td = document.createElement('TD');
td.width = '75';
td.appendChild(document.createTextNode("text"));
tr.appendChild(td);
}
}
myTableDiv.appendChild(table);
}
addTable();
You need to create an input element and then append that to td:
rn = window.prompt("Input number of rows", 1);
cn = window.prompt("Input number of columns", 1);
var myTableDiv = document.getElementById("myDynamicTable");
var table = document.createElement('TABLE');
table.border = '1';
var tableBody = document.createElement('TBODY');
table.appendChild(tableBody);
for (var i = 0; i < parseInt(rn, 10); i++) {
var tr = document.createElement('TR');
tableBody.appendChild(tr);
for (var j = 0; j < parseInt(cn, 10); j++) {
var td = document.createElement('TD');
td.width = '75';
var input = document.createElement('input');
input.setAttribute('type', 'text');
input.setAttribute('value', 'text');
td.appendChild(input);
tr.appendChild(td);
}
}
myTableDiv.appendChild(table);
<div id="myDynamicTable">
</div>
You can use contenteditable attribute: td.contenteditable = 'true';.
Depending on how you want to use this value, you might also insert an input element.
You are perhaps looking for contentEditable?
function addTable() {
const rn = +window.prompt("Input number of rows", 1);
const cn = +window.prompt("Input number of columns", 1);
const myTableDiv = document.getElementById("myDynamicTable");
const table = document.createElement('table');
table.border = '1';
const tableBody = document.createElement('tbody');
table.appendChild(tableBody);
for (let i = 0; i < rn; i++) {
var tr = document.createElement('tr');
tableBody.appendChild(tr);
for (let j = 0; j < cn; j++) {
var td = document.createElement('td');
td.width = '75';
td.contentEditable = true;
td.appendChild(document.createTextNode("text"));
tr.appendChild(td);
}
}
myTableDiv.appendChild(table);
}
addTable();
<div id="myDynamicTable"></div>
if you want to operate on tables, use corrects javascript instructions ...
const
DynTb = document.getElementById('myDynamicTable')
rn = +window.prompt("Input number of rows", 1)
, cn = +window.prompt("Input number of columns", 1)
;
if( isNaN(rn) || isNaN(cn))
throw 'bad integer input value (s)'
const myTable = addTable(DynTb, rn, cn )
function addTable(tDiv, rn, cn)
{
let
tab = tDiv.appendChild( document.createElement('table') )
, tBy = tab.createTBody()
;
for(let r=0;r<rn;++r)
{
let row = tBy.insertRow()
for(let c=0;c<cn;++c)
{
row.insertCell().innerHTML =
`<input type="text" placeHolder="${r}-${c}">`
} }
return tab
}
table {
border-collapse : collapse;
margin : 2em 1em;
}
td {
padding : .2em;
border : 1px solid darkblue;
}
input {
width : 5em;
}
<div id="myDynamicTable"></div>

JS and DOM, trying to create table

I tried to create table but I can't create td in every tr, td is creating only in first td what is in table, how I can solve the problem?
// Creating div
var main = document.createElement("div")
main.innerHTML = ""
document.body.appendChild(main)
main.setAttribute("id", "main")
//Creating Icons
var puzzleico = document.createElement("div")
puzzleico.innerHTML = ""
document.getElementById("main").appendChild(puzzleico)
puzzleico.setAttribute("id", "puzzleico")
var puzzleico = document.getElementById("puzzleico").onclick = function() {createtable()};
//Creating tr and td
function createtable() {
//Creating Table
var table = document.createElement("table")
table.innerHTML = ""
document.body.appendChild(table)
table.setAttribute("id", "table")
for (var i = 0; i < 50; i++) {
var tr = document.createElement("tr")
tr.innerHTML = ""
document.getElementById("table").appendChild(tr)
tr.setAttribute("id", "tr")
var td = document.createElement("td")
td.innerHTML = ""
document.getElementById("tr").appendChild(td)
}
}
Element id's within a document need to be unique. The issue here is that your document.getElementById("tr") will always return the first element it finds with that id and so, all of your <td> elements will be appended to the first <tr>.
In order to fix it you can remove the tr.setAttribute("id", "tr") line and use the already existing tr variable to append the td child to.
function createtable() {
//Creating Table
var table = document.createElement("table")
table.innerHTML = ""
document.body.appendChild(table)
table.setAttribute("id", "table")
for (var i = 0; i < 50; i++) {
var tr = document.createElement("tr")
tr.innerHTML = ""
document.getElementById("table").appendChild(tr);
var td = document.createElement("td");
td.innerHTML = "test"
tr.appendChild(td)
}
}
createtable();
The above code will work, but using the already declared variables instead of finding them again can also be applied to the table case. Also, table.innerHTML = "" doesn't add any value because the innerHTML is already empty when you create a new element.
function createtable() {
//Creating Table
var table = document.createElement("table");
document.body.appendChild(table);
for (var i = 0; i < 50; i++) {
var tr = document.createElement("tr");
table.appendChild(tr);
var td = document.createElement("td");
td.innerHTML = "test";
tr.appendChild(td);
}
}
You can use this to create the table:
function createTable(){
//Creating And Appending Child
let table = document.createElement('table');
document.body.appendChild(table);
for(let i = 0; i < 50; i++){
let tr = document.createElement('tr');
let td = document.createElement('td');
td.innerHTML = i;
tr.appendChild(td);
table.appendChild(tr);
}
}
Here is the link to my codepen:
https://codepen.io/prabodhpanda/pen/gOPLqYe?editors=1010
id attribute of each element in DOM should be unique. You set same id for each tr element you create. document.getElementById element always returns the first element match by the id. This is the reason of the issue. Your last code snippet should be:
function createtable() {
//Creating Table
var table = document.createElement("table")
table.innerHTML = ""
document.body.appendChild(table)
table.setAttribute("id", "table")
for (var i = 0; i < 50; i++) {
var tr = document.createElement("tr")
tr.innerHTML = ""
document.getElementById("table").appendChild(tr)
tr.setAttribute("id", "tr" + i) // Check this
var td = document.createElement("td")
td.innerHTML = ""
document.getElementById("tr" + i).appendChild(td) // Check this
}
}
tr.appendChild(td) should also work if you don't need ID attribute.
I edited your answer and got what I want.
//Creating tr and td
function createtable() {
//Creating Table
var table = document.createElement("table")
table.innerHTML = ""
document.body.appendChild(table)
table.setAttribute("id", "table")
for (var i = 0; i < 50; i++) {
var tr = document.createElement("tr")
tr.innerHTML = ""
document.getElementById("table").appendChild(tr)
tr.setAttribute("id", "tr")
for (var v = 0; v < 50; v++) {
var td = document.createElement("td")
td.innerHTML = ""
tr.appendChild(td)
}
}
}

convert json data to pdf using jQuery

I want to export JSON data to pdf with out using any third party plugin.I am having data in Json and need to display data in pdf table structure using JQuery. Please let me know if its possible.
Here is sample JSON
jsonResult.Products[
{PRODUCT_ID: 123, PRODUCT_NUMBER: "00022", PRODUCT_NAME: "HONDA", PRODUCT_TYPE: "VEHICLE "},
{PRODUCT_ID: 783, PRODUCT_NUMBER: "08412394", PRODUCT_NAME: "HONDA", PRODUCT_TYPE: "MOTOR "}.....]
Code snippet using jS PDF-autotable
<script src="~/Scripts/JsPDF-Autotable.js"></script>
$("#btnExportPDF").click(function () {
let table = document.createElement('table');
table.setAttribute("id", "pdfTable");
let thead = document.createElement('thead');
let tbody = document.createElement('tbody');
let thead_tr = document.createElement('tr');
let sample = dataResult.Cases[0];
let columns = [];
let columnData = [];
for (let column in sample) columns.push(column);
for (let i = 0; i < columns.length; i++) {
let th = document.createElement('th');
th.innerText = columns[i];
thead_tr.appendChild(th);
}
thead.appendChild(thead_tr);
for (let i = 0; i < dataResult.Cases.length; i++) {
let tr = document.createElement('tr');
let product = dataResult.Cases[i];
for (let column = 0; column < columns.length; column++) {
let td = document.createElement('td');
td.innerText = product[columns[column]];
columnData.push(product[columns[column]]);
tr.appendChild(td);
}
tbody.appendChild(tr);
}
table.appendChild(thead);
table.appendChild(tbody);
var doc = new jsPDF('p', 'pt');
doc.autoTable(columns, columnData)
doc.save("table.pdf");
});
I tried to export to pdf using jspdf autotable and I am getting below error
JsPDF-Autotable.js:1538 Use of deprecated autoTable initiation
Yes it's definitely possible.
The process is very simple:
Prepare your JSON data
Create a table element filled with your data
Export table with JSPDF
Creating the table
let table = document.createElement('table');
let thead = document.createElement('thead');
let tbody = document.createElement('tbody ');
let thead_tr = document.createElement('tr');
let sample = jsonResult.Products[0];
let columns = [];
for (let column in sample) columns.push(column);
for (let i = 0; i<columns.length;i++){
let th = document.createElement('th');
th.innerText = columns[i];
thead_tr.appendChild(th);
}
thead.appendChild(thead_tr);
for (let i = 0; i<jsonResult.Products.length;i++){
let tr = document.createElement('tr');
let product = jsonResult.Products[i];
for (let column = 0; column < columns.length; column++){
let td = document.createElement('td');
td.innerText = product[columns[column]];
tr.appendChild(td);
}
tbody.appendChild(tr);
}
table.appendChild(thead);
table.appendChild(tbody);
document.body.appendChild(table); // Now this is your table which you are going to export
Follow this SO answer/guide to export the HTML table with JSPDF

How to make table with nested loop in JS

How to make the middle Column to be X rather than 0.
Here is my code:
var table = document.createElement('table'), tr, td, row, cell;
for (row = 0; row < 3; row++) {
tr = document.createElement('tr');
for (cell = 0; cell < 3; cell++) {
td = document.createElement('td');
tr.appendChild(td);
td.innerHTML = 0
}
table.appendChild(tr);
}
document.getElementById('container').appendChild(table);
<div id="container"></div>
You could add a check if the cell is 1. Then take an 'X'.
var table = document.createElement('table'),
tr, td, row, cell;
for (row = 0; row < 3; row++) {
tr = document.createElement('tr');
for (cell = 0; cell < 3; cell++) {
td = document.createElement('td');
tr.appendChild(td);
td.innerHTML = cell === 1 ? 'X' : 0;
}
table.appendChild(tr);
}
document.getElementById('container').appendChild(table);
<div id="container">
</div>
One option is to use switch:
var table = document.createElement('table');
for (var row = 0; row < 3; row++) {
var tr = document.createElement('tr');
for (var cell = 0; cell < 3; cell++) {
var td = document.createElement('td');
//console.log(cell);
var cellText = "";
// This switch picks content based on cell order
switch(cell) {
case 0: cellText = "0"; break;
case 1: cellText = "X"; break;
case 2: cellText = "0"; break;
// Default value if cell count changes
default: cellText = "Unknown cell!";
}
// Using `new Text` ensures the value is entered as text, not HTML
// This can protect you from XSS or unexpected behavior
td.appendChild(new Text(cellText));
tr.appendChild(td);
}
table.appendChild(tr);
}
document.getElementById('container').appendChild(table);
<div id="container">
</div>
It's not the most maintainable solution, but good enough for simple script.

Some misunderstanding with creating dynamic table in JavaScript

I try to create dynamic table using JavaScript, the table contains two columns first name and family name.
Here is the JavaScropt code:
function CreatTable() {
var tablearea = document.getElementById('ShowDataID');
var table = document.createElement('table');
var thead = document.createElement("thead");
var tr = document.createElement('tr');
var th = document.createElement('th');
var firstNameTxt = document.createTextNode("First Name");
th.appendChild(firstNameTxt);
tr.appendChild(th);
thead.appendChild(tr);
table.appendChild(thead);
var familyNameTxt = document.createTextNode("Family Name");
th.appendChild(familyNameTxt);
tr.appendChild(th);
thead.appendChild(tr);
table.appendChild(thead);
for (var i = 1; i < 4; i++) {
var tr = document.createElement('tr');
tr.appendChild(document.createElement('td'));
tr.appendChild(document.createElement('td'));
tr.cells[0].appendChild(document.createTextNode('John'))
tr.cells[1].appendChild(document.createTextNode('McDowell'))
table.appendChild(tr);
}
tablearea.appendChild(table);
}
And here the the result I get:
My question is why do I get "McDowell" not under the family name column.Why it is shifted?What I am missing?
Try to create a new th for the second time, don't use the already used one
function CreatTable() {
var tablearea = document.getElementById('ShowDataID');
var table = document.createElement('table');
var thead = document.createElement("thead");
var tr = document.createElement('tr');
var th = document.createElement('th');
var firstNameTxt = document.createTextNode("First Name");
th.appendChild(firstNameTxt);
tr.appendChild(th);
thead.appendChild(tr);
table.appendChild(thead);
//********* Look here *****************
var familyNameTxt = document.createTextNode("Family Name");
th = document.createElement('th'); //*** Create a new th here. Dont use the old one
//********* Look here *****************
th.appendChild(familyNameTxt);
tr.appendChild(th);
thead.appendChild(tr);
table.appendChild(thead);
for (var i = 1; i < 4; i++) {
var tr = document.createElement('tr');
tr.appendChild(document.createElement('td'));
tr.appendChild(document.createElement('td'));
tr.cells[0].appendChild(document.createTextNode('John'))
tr.cells[1].appendChild(document.createTextNode('McDowell'))
table.appendChild(tr);
}
tablearea.appendChild(table);
}
DEMO
SOLUTION
function CreatTable() {
var tablearea = document.getElementById('ShowDataID');
var table = document.createElement('table');
var thead = document.createElement('thead');
var tr = document.createElement('tr');
var th = document.createElement('th');
var firstNameTxt = document.createTextNode("First Name");
th.appendChild(firstNameTxt);
tr.appendChild(th);
thead.appendChild(tr);
table.appendChild(thead);
var familyNameTxt = document.createTextNode("Family Name");
th = document.createElement('th');
th.appendChild(familyNameTxt);
tr.appendChild(th);
thead.appendChild(tr);
table.appendChild(thead);
for (var i = 1; i < 4; i++) {
tr = document.createElement('tr');
tr.appendChild(document.createElement('td'));
tr.appendChild(document.createElement('td'));
tr.cells[0].appendChild(document.createTextNode('John'));
tr.cells[1].appendChild(document.createTextNode('McDowell'));
table.appendChild(tr);
}
tablearea.appendChild(table);
}
CreatTable();
you miss creating new th
var familyNameTxt = document.createTextNode("Family Name");
th = document.createElement('th'); // this line missed
th.appendChild(familyNameTxt);
Create dynamic table row and remove on click delete button row. for this you can use jQuery two method
.append() this method used for append html table row, on button click of .add_row_record its get value from text box and append data on table row.
.remove () this method is used for remove dynamic content data, in this example we are used for delete append record. .delete_row_record button remove the record on the basis of selected checkbox.
<script type="text/javascript">
$(document).ready(function(){
//add row
$(".add_row_record").click(function(){
var name = $("#name").val();
var email = $("#email").val();
var mobile = $("#mobile_number").val();
var markup = "<tr><td><input type='checkbox' name='record'></td><td>" + name + "</td><td>" + email + "</td><td>" + mobile + "</td></tr>";
$("table tbody").append(markup);
});
// select record for delete
$(".delete_row_record").click(function(){
$("table tbody").find('input[name="record"]').each(function(){
if($(this).is(":checked")){
$(this).parents("tr").remove();
}
});
});
});
Demo

Categories

Resources