How to generate table from HTML? - javascript

So, I have to generate multiple tables from the HTML code. I can be generating multiple tables using pure javascript code but its too difficult to assign ids and getting its value. as I wrote javascript function generate_table
so I have created one sample HTML table from that HTML TAble how to generate the same Table again(multiple times). I have written too much javascript code for tables TD and TR. How to reduce that code.
I have many tables I want to regenerate the specific table so I cant use <table> tag. Any hint ? code sample ?
function generate_table() {
// get the reference for the body
var body = document.getElementsByTagName('body')[0];
// creates a <table> element and a <tbody> element
var tbl = document.createElement('table');
var tblBody = document.createElement('tbody');
// creating all cells
for (var i = 0; i < 1; i++) {
var seqnumber = 1;
var seq = +1;
// creates a table row
var row2 = document.createElement('tr');
//====== table first row data =======//
var seq = document.createElement('td');
var seqText = document.createTextNode('Seq');
var l = document.createElement('td');
var seqText1 = document.createElement('input');
//===== seq generator =====//
seq.appendChild(seqText);
row2.appendChild(seq);
l.appendChild(seqText1);
row2.appendChild(l);
// add the row to the end of the table body
tblBody.appendChild(row2);
}
// put the <tbody> in the <table>
tbl.appendChild(tblBody);
// appends <table> into <body>
body.appendChild(tbl);
// sets the border attribute of tbl to 2;
tbl.setAttribute('border', '2');
}
td,
th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
<h3> TABLE FROM JAVA SCRIPT</h3>
<input type="button" value="Generate a table." onclick="generate_table()" />
<h3> TABLE FROM HTML</h3>
<table id="table6">
<tr>
<th colspan="2">Aggregator</th>
</tr>
<tr>
<th> Column Name </th>
<th> Function </th>
</tr>
<tr>
<td> <input> </td>
<td> <input> </td>
</tr>
</table>
<input type="button" value="Generate same table from HTML." />
JSfiddle Link : - >https://jsfiddle.net/shreekantbatale2/evqsuxm8/5/

What I understand is that you want to add a template table. Here is a simple way to do it with jQuery
var id = 0;
function generate_table() {
var table = `<table id='table${id}'>
<tr>
<th colspan="2">Aggregator</th>
</tr>
<tr>
<th> Column Name </th>
<th> Function </th>
</tr>
<tr>
<td> <input> </td>
<td> <input> </td>
</tr>
</table>`
$('#table-template').append(table)
id++
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h3> TABLE FROM JAVA SCRIPT</h3>
<input type="button" value="Generate a table." onclick="generate_table()" />
<h3> TABLE FROM HTML</h3>
<div id='table-template'></div>
<input type="button" value="Generate same table from HTML." />
I think this is what you are lookign for.
function generate_table() {
var table = $('#table6').clone()
table.find('input').val('')
$('#table-template').append(table)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h3> TABLE FROM JAVA SCRIPT</h3>
<input type="button" value="Generate a table." onclick="generate_table()" />
<h3> TABLE FROM HTML</h3>
<table id='table6'>
<tr>
<th colspan="2">Aggregator</th>
</tr>
<tr>
<th> Column Name </th>
<th> Function </th>
</tr>
<tr>
<td> <input> </td>
<td> <input> </td>
</tr>
</table>
<input type="button" value="Generate same table from HTML." />
<div id='table-template'></div>

You could use a <template> element to generate new HTML each time you want a new <table>
const button = document.querySelector('.js-create-table');
const template = document.createElement('template');
template.innerHTML = `
<table>
<tr>
<th colspan="2">Aggregator</th>
</tr>
<tr>
<th> Column Name </th>
<th> Function </th>
</tr>
<tr>
<td> <input> </td>
<td> <input> </td>
</tr>
</table>
`;
function generateTable() {
const table = template.content.cloneNode(true);
document.body.append(table);
}
button.addEventListener('click', generateTable);
<button class="js-create-table">Create table</button>
And if you just want to clone the original table and create a duplicate from it one.
const button = document.querySelector('.js-clone-table');
const table = document.querySelector('.js-table');
function cloneTable() {
const clone = table.cloneNode(true);
document.body.append(clone);
}
button.addEventListener('click', cloneTable);
<button class="js-clone-table">Clone table</button>
<table class="js-table">
<tr>
<th colspan="2">Aggregator</th>
</tr>
<tr>
<th> Column Name </th>
<th> Function </th>
</tr>
<tr>
<td> <input> </td>
<td> <input> </td>
</tr>
</table>

to duplicater a table with everyting inside (or any html element)
const btTableCopy = document.getElementById('bt-table-copy')
, originTable = document.getElementById('table6')
, baseRowTbl = originTable.querySelector('tbody tr')
;
var tableNum = 0
;
btTableCopy.onclick=()=>
{
let newTable = originTable.cloneNode(true)
, newTbody = newTable.querySelector('tbody')
;
newTable.id = `table-copy-${++tableNum}` // there cannot be two identical id values on an HTML page
for(let i=0;i<5;i++) // add 5 new rows
{
newTbody.appendChild(baseRowTbl.cloneNode(true))
}
newTable.querySelectorAll('input').forEach(inp=>inp.value='') // clear all table inputs
document.body.appendChild(newTable)
}
table {
border-collapse: collapse;
margin: 1em;
}
thead {
background-color: lightblue;
}
td, th {
border: solid grey 1px;
padding: 1em;
text-align : center;
}
<table id="table6">
<thead>
<tr>
<th colspan="2">Aggregator</th>
</tr>
<tr>
<th> Column Name </th>
<th> Function </th>
</tr>
</thead>
<tbody>
<tr>
<td> <input> </td>
<td> <input> </td>
</tr>
</tbody>
</table>
<button id="bt-table-copy">copy table with 5 new rows</button>

Related

jQuery appendTo ignoring last element

I'm trying to append a copy of an element to the bottom of the parent element. It seems to append everything above the last element within the parent. Live example on JSFiddle
var count = 1;
$("#addBtn").click(function(){
$('#trid1').clone().appendTo('table#exampleTable > tbody');
count++;
$('#trid1').last().prop('id', 'trid'+count);
$('#trid'+count+' > th').html(count);
});
<!-- jQuery -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table" id="exampleTable">
<thead>
<tr>
<th scope="col">c1</th>
</tr>
</thead>
<tbody>
<tr id="trid1" class="trclass">
<th scope="row">1</th>
</tr>
</tbody>
</table>
<button type="button" id="addBtn">Add</button>
I would change the id before appending the new element to the DOM.
Anyway I slightly refactored your code with that strategy in mind and better dealt with the current index every time you click the add button. The latest index gets saved in a data attribute in the table.
$("#addBtn").click(function(){
const latestIndex = $('#exampleTable').data('latest-index');
let i = latestIndex+1;
const newRow = $('#trid1').clone();
newRow.prop('id', `trid${i}`);
newRow.data('index', i);
newRow.text(i);
newRow.appendTo('table#exampleTable > tbody');
$('#exampleTable').data('latest-index', i);
});
button{
cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table" id="exampleTable" data-latest-index="1">
<thead>
<tr>
<th scope="col">Rows</th>
</tr>
</thead>
<tbody>
<tr id="trid1" class="trclass">
<th scope="row">1</th>
</tr>
</tbody>
</table>
<button type="button" id="addBtn">Add</button>

How to add Row into dynamic html table?

I have created one div that is not visible, in that div main table is hidden and I'm cloning that table into another div. that div id is main-div.
I want to add a row into that newly generated table? how to append rows using jQuery?
generate table function, delete table function, and remove row function are in working condition.
adding new row using javascript or Jquery which better way to handle? any hint?
// ==================== //
// Add aggregate Table//
// ==================== //
var aggTableNum = 0;
$('.addAggregatorCompo').click(function (e) {
const originTable = document.getElementById('aggregator-table');
let newTable = originTable.cloneNode(true);
newTable.id = 'newAggTable' + ++aggTableNum;
newTable.querySelectorAll('input').forEach((element) => {
element.value = '';
});
$('#main-div').append(newTable);
});
// ==================== //
// Delete Component //
// ==================== //
$('#main-div').on('click', '.delete-component', function (e) {
e.preventDefault(); // in case it is not a type=button and the table is wrapped in a form
this.closest('table').remove();
});
// ==================== //
// Delete Records//
// ==================== //
$('#main-div').on('click', '.delete-record', function () {
$('table tbody')
.find('input[name="record"]')
.each(function () {
if ($(this).is(':checked')) {
$(this).parents('tr').remove();
}
});
});
// ==================== //
// Add Aggregate records //
// ==================== //
$('#main-div').on('click', '.add-record', function () {
$('<tr>')
.append($('<td>').append('input'))
.append($('<td>').append('text2'))
.append($('<td>').append('text3'))
.append($('<td>').append('text4'));
});
#aggregator-table {
display: none;
}
table {
border-collapse: collapse;
margin: 1em;
}
thead {
background-color: lightblue;
}
td,
th {
border: solid grey 1px;
padding: 1em;
text-align: center;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button style="margin: 1%" class="addAggregatorCompo">Add Table</button>
<table id="aggregator-table" class="component-base">
<thead>
<th colspan="6">Aggregator</th>
<tr>
<th> Select</th>
<th> Column 1 </th>
<th> Column 2 </th>
<th> Column 3 </th>
<th> Column 4 </th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="checkbox" name="record"></td>
<td>
<input id='column1'>
</input>
</td>
<td><input id="column2">
</input></td>
<td>
<input id="column3">
</input>
</td>
<td>
<input id="4">
</input>
</td>
</tr>
<tr>
<td>
<button style="margin: 1%" class="add-record">add Record</button>
</td>
<td>
<button class="delete-component" style="margin: 1%">Delete Table </button>
</td>
<td>
<button class="delete-record" style="margin: 1%">Delete Record </button>
</td>
</tr>
</tbody>
</table>
<div class="generate-div" id="main-div"></div>
jsFiddle - >https://jsfiddle.net/shreekantbatale2/h2sv1q9p/
You've done the work of creating the new tr in memory. All you need to do is add it to the DOM. This can be achieved using appendTo():
$('#main-div').on('click', '.add-record', function() {
let $tbody = $(this).closest('tbody');
$('<tr>')
.append($('<td>').append('input'))
.append($('<td>').append('text2'))
.append($('<td>').append('text3'))
.append($('<td>').append('text4'))
.appendTo($tbody);
});
// ==================== //
// Add aggregate Table//
// ==================== //
var aggTableNum = 0;
$('.addAggregatorCompo').click(function(e) {
const originTable = document.getElementById('aggregator-table');
let newTable = originTable.cloneNode(true);
newTable.id = 'newAggTable' + ++aggTableNum;
newTable.querySelectorAll('input').forEach((element) => {
element.value = '';
});
$('#main-div').append(newTable);
});
// ==================== //
// Delete Component //
// ==================== //
$('#main-div').on('click', '.delete-component', function(e) {
e.preventDefault(); // in case it is not a type=button and the table is wrapped in a form
this.closest('table').remove();
});
// ==================== //
// Delete Records//
// ==================== //
$('#main-div').on('click', '.delete-record', function() {
$('table tbody')
.find('input[name="record"]')
.each(function() {
if ($(this).is(':checked')) {
$(this).parents('tr').remove();
}
});
});
// ==================== //
// Add Aggregate records //
// ==================== //
$('#main-div').on('click', '.add-record', function() {
let $tbody = $(this).closest('table').find('tbody');
$('<tr>')
.append($('<td>').append('input'))
.append($('<td>').append('text2'))
.append($('<td>').append('text3'))
.append($('<td>').append('text4'))
.appendTo($tbody);
});
#aggregator-table {
display: none;
}
table {
border-collapse: collapse;
margin: 1em;
}
thead {
background-color: lightblue;
}
td,
th {
border: solid grey 1px;
padding: 1em;
text-align: center;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button style="margin: 1%" class="addAggregatorCompo">Add Table</button>
<table id="aggregator-table" class="component-base">
<thead>
<th colspan="6">Aggregator</th>
<tr>
<th>Select</th>
<th>Column 1</th>
<th>Column 2</th>
<th>Column 3</th>
<th>Column 4</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="checkbox" name="record"></td>
<td><input id="column1" /></td>
<td><input id="column2" /></td>
<td><input id="column3" /></td>
<td><input id="4" /></td>
</tr>
</tbody>
<tfoot>
<tr>
<td>
<button style="margin: 1%" class="add-record">add Properties</button>
</td>
<td>
<button class="delete-component" style="margin: 1%">Delete Table </button>
</td>
<td>
<button class="delete-record" style="margin: 1%">Delete Record </button>
</td>
</tr>
</tfoot>
</table>
<div class="generate-div" id="main-div"></div>
Also note in your HTML that <input /> elements do not have a closing tag.

Appending a tr element to the tbody element on the click of a button

I'm trying to create button event listener that will add the contents of a <tr> element to the <tbody> element. Ive tried multiple methods such as insertRow() and adjacentHtml() and none seem to work. What am I doing wrong? also i am using typescript, could that be the issue as well?
html
<table class="table table-striped table-dark invoice-table">
<thead>
<tr class="head-contents">
<th scope="col">#</th>
<th scope="col-3">Description</th>
<th scope="col">Quanity</th>
<th scope="col">item number</th>
<th scope="col">item price</th>
<th scope="col">total price</th>
</tr>
</thead>
<tbody id="table-contents">
<tr id="item-info">
<th scope="row">1</th>
<td><input type="text"></td>
<td><input type="number"></td>
<td><input type="number"></td>
<td><input type="number"></td>
<td><span></span></td>
</tr>
</tbody>
</table>
<!-- add item button -->
<button type="button" class="btn btn-primary" id="addItem">Add Item</button>
<!-- delete item button -->
<button type="button" class="btn btn-warning" id="deleteItem">Delete Item</button>
javascript
// event listener to add an item
let addedItem = document.getElementById("addItem").addEventListener("click", () => {
let table = document.getElementById("invoice-table");
let row = document.getElementById("item-info");
});;
<table class="table table-striped table-dark invoice-table">
<thead>
<tr class="head-contents">
<th scope="col">#</th>
<th scope="col-3">Description</th>
<th scope="col">Quanity</th>
<th scope="col">item number</th>
<th scope="col">item price</th>
<th scope="col">total price</th>
</tr>
</thead>
<tbody id="table-contents">
<tr id="item-info">
<th scope="row">1</th>
<td><input type="text"></td>
<td><input type="number"></td>
<td><input type="number"></td>
<td><input type="number"></td>
<td><span></span></td>
</tr>
</tbody>
</table>
<button id="addItem">Add Item</button>
<script>
document.getElementById('addItem').addEventListener('click', () => {
let body = document.getElementById("table-contents");
let row = document.getElementById("item-info");
var para = document.createElement("tr")
para.innerHTML = `
<th scope="row">1</th>
<td><input type="text"></td>
<td><input type="number"></td>
<td><input type="number"></td>
<td><input type="number"></td>
<td><span></span></td>
`;
body.appendChild(para);
})
</script>
You need to create a template and then append to it every time you click on the button.
let addedItem = document.getElementById("addItem").addEventListener("click", () => {
let item = document.getElementById("table-contents");
item.insertAdjacentHTML('beforeend', "<tr id='item-info'> <th scope='row'>1</th> <td><input type='text'></td> <td><input type='number'></td> <td><input type='number'></td> <td><input type='number'></td> <td><span></span></td></tr>");
});;
Don't forget the button within your HTML:
<button id="addItem">Add New Row</button>
This worked for me, let me know if you have more questions.
Check out the code snippet. This code worked for me. Depending on what actually you want to archive you can/ should tweak this to your needs. Like adding an id that actually increments with each row, and making an additional function to calculate your Total columns.
But since that wasn't included in the answer, I leave that up to you :)
// ARRAY FOR HEADER.
const arrHead = ['#', 'One', 'Two', 'Three'];
// SIMPLY ADD OR REMOVE VALUES IN THE ARRAY FOR TABLE HEADERS.
// FIRST CREATE A TABLE STRUCTURE BY ADDING A FEW HEADERS AND
// ADD THE TABLE TO YOUR WEB PAGE.
function createTable() {
var empTable = document.createElement('table');
empTable.setAttribute('id', 'empTable'); // SET THE TABLE ID.
var tr = empTable.insertRow(-1);
for (var h = 0; h < arrHead.length; h++) {
var th = document.createElement('th'); // TABLE HEADER.
th.innerHTML = arrHead[h];
tr.appendChild(th);
}
var div = document.getElementById('cont');
div.appendChild(empTable); // ADD THE TABLE TO YOUR WEB PAGE.
}
// ADD A NEW ROW TO THE TABLE
function addRow() {
var empTab = document.getElementById('empTable');
var rowCnt = empTab.rows.length; // GET TABLE ROW COUNT.
var tr = empTab.insertRow(rowCnt); // TABLE ROW.
tr = empTab.insertRow(rowCnt);
for (var c = 0; c < arrHead.length; c++) {
var td = document.createElement('td'); // TABLE DEFINITION.
td = tr.insertCell(c);
if (c == 0) { // FIRST COLUMN.
// ADD A BUTTON.
var button = document.createElement('input');
// SET INPUT ATTRIBUTE.
button.setAttribute('type', 'button');
button.setAttribute('value', 'Remove');
// ADD THE BUTTON's 'onclick' EVENT.
button.setAttribute('onclick', 'removeRow(this)');
td.appendChild(button);
}
else {
// CREATE AND ADD TEXTBOX IN EACH CELL.
var ele = document.createElement('input');
ele.setAttribute('type', 'text');
ele.setAttribute('value', '');
td.appendChild(ele);
}
}
}
// DELETE TABLE ROW.
function removeRow(oButton) {
var empTab = document.getElementById('empTable');
empTab.deleteRow(oButton.parentNode.parentNode.rowIndex); // BUTTON -> TD -> TR.
}
// EXTRACT AND SUBMIT TABLE DATA.
function sumbit() {
var myTab = document.getElementById('empTable');
var values = new Array();
// LOOP THROUGH EACH ROW OF THE TABLE.
for (row = 1; row < myTab.rows.length - 1; row++) {
for (c = 0; c < myTab.rows[row].cells.length; c++) { // EACH CELL IN A ROW.
var element = myTab.rows.item(row).cells[c];
if (element.childNodes[0].getAttribute('type') == 'text') {
values.push(element.childNodes[0].value);
}
}
}
console.log(values);
}
table
{
width: 70%;
font: 17px Calibri;
}
table, th, td
{
border: solid 1px #DDD;
border-collapse: collapse;
padding: 2px 3px;
text-align: center;
color: green;
}
<body onload="createTable()">
<input type="button" id="addRow" value="Add New Row" onclick="addRow()" />
</p>
<!--THE CONTAINER WHERE WE'll ADD THE DYNAMIC TABLE-->
<div id="cont"></div>
<p><input type="button" id="bt" value="Sumbit Data" onclick="sumbit()" /></p>
</body>

How to copy the contents of one row in a table to another table and add the identical ones

var Sell_Button = document.getElementById('sellbtn'),
secondTable = document.getElementById("secondTableBody");
Sell_Button.addEventListener('click', function() {
var Row = secondTable.insertRow();
for (var c = 0; c < 2; c += 1) {
Row.insertCell(c);
}
Row.cells[0].innerHTML = this.parentNode.parentNode.cells[0].innerHTML;
Row.cells[2].innerHTML = this.parentNode.parentNode.cells[1].innerHTML;
//checks to see if the secondTable has a row containing the same name
for (var f = 0; f < secondTable.rows.length; f += 1) {
//adds only the sold amount if the second table has a row with the same name
//error
if (secondTable.rows[f].cells[0].innerText === this.parentNode.parentNode.cells[0].innerText) {
secondTable.rows[f].cells[1].innerHTML = +this.parentNode.parentNode.cells[2].innerHTML;
//deletes an extra row that is added at the bottom
if (secondTable.rows.length > 1) {
secondTable.deleteRow(secondTable.rows.length - 1);
}
//if nothing matched then a new row is added
} else {
secondTable.insertRow();
Row.cells[0].innerHTML = this.parentNode.parentNode.cells[0].innerHTML;
Row.cells[1].innerHTML = this.parentNode.parentNode.cells[2].innerHTML;
}
}
}
}
<html>
<body>
<div id="firstTableDiv">
<table border="1" id="firstTable">
<thead>
<th>Item</th>
<th>Stock</th>
<th colspan="1">Sold</th>
</thead>
<tbody id="firstTableBody">
<tr>
<td>Apples</td>
<td>300</td>
<td>200</td>
<td>
<button id="sellbtn">Sell</button>
</td>
</tr>
<tr>
<td>Apples</td>
<td>300</td>
<td>100</td>
<td>
<button id="sellbtn">Sell</button>
</td>
</tr>
<tr>
<td>Oranges</td>
<td>400</td>
<td>300</td>
<td>
<button id="sellbtn">Sell</button>
</td>
</tr>
</tbody>
</table>
</div>
</br>
<div id="secondTableDiv">
Sold
<table border="1" id="secondTable">
<thead>
<th>Item</th>
<th>Sold</th>
</thead>
<tbody id="secondTableBody">
</tbody>
</table>
</div>
</body>
</html>
Ok, this example isn't exactly what i'm working on but it's very similar. The only difference is that in mine the rows and buttons are dynamically added by the user and he inserts the details. What I want is that when i press on the button of each row (sell) the details (Item and Sold only) are copied into a row in the second table and checks if the same item exists in this second table if so then it adds the amount of sold of both items in one row. For instance I press on the first row button the Apples it copies the listed above details to the second table in a row and then when i click on the button of the second row (Apples also) it only adds the sold amount up and doesn't add a second apples row because an apples row already exists in the second table but when i click on the oranges button it makes a new row because the oranges row doesn't exist. So how do I do this in JavaScript? i hope i was thorough and made any sense. I have no idea why the code isn't working here but i hope you get the point. This code works perfectly just as i want it to until for some reason i get this error: Cannot read property 'innerText' of undefined when i press the buttons approx. 6-7 times targeting the if statement where i commented error.
This sets a click handler to all buttons. If the row doesn't exist in the second table it's created. It sets a data-type referring to the item. When somebody clicks the sell button again and there is a row containing the data-type the row is updated instead of created. All in plain JavaScript.
var Sell_Button = document.querySelectorAll('.sellbtn'),
secondTable = document.getElementById("secondTableBody");
Array.prototype.slice.call(Sell_Button).forEach(function(element){
element.addEventListener('click', function(e) {
//since the button is an element without children use e.
var clickedElement = e.target;
var parentRow = clickedElement.parentNode.parentNode;
//check if second table has a row with data-type
var rowWithData = secondTable.querySelector("[data-type='"+parentRow.cells[0].childNodes[0].nodeValue+"']");
if (rowWithData)
{
rowWithData.cells[1].innerHTML = parseInt(rowWithData.cells[1].childNodes[0].nodeValue) + parseInt(parentRow.cells[2].childNodes[0].nodeValue);
}
else
{
var Row = secondTable.insertRow();
Row.setAttribute("data-type", parentRow.cells[0].childNodes[0].nodeValue);
for (var c = 0; c < 2; c += 1) {
Row.insertCell(c);
}
Row.cells[0].innerHTML = parentRow.cells[0].childNodes[0].nodeValue;
Row.cells[1].innerHTML = parentRow.cells[2].childNodes[0].nodeValue;
}
});
});
<html>
<body>
<div id="firstTableDiv">
<table border="1" id="firstTable">
<thead>
<th>Item</th>
<th>Stock</th>
<th colspan="1">Sold</th>
</thead>
<tbody id="firstTableBody">
<tr>
<td>Apples</td>
<td>300</td>
<td>200</td>
<td>
<button class="sellbtn">Sell</button>
</td>
</tr>
<tr>
<td>Apples</td>
<td>300</td>
<td>100</td>
<td>
<button class="sellbtn">Sell</button>
</td>
</tr>
<tr>
<td>Oranges</td>
<td>400</td>
<td>300</td>
<td>
<button class="sellbtn">Sell</button>
</td>
</tr>
</tbody>
</table>
</div>
</br>
<div id="secondTableDiv">
Sold
<table border="1" id="secondTable">
<thead>
<th>Item</th>
<th>Sold</th>
</thead>
<tbody id="secondTableBody">
</tbody>
</table>
</div>
</body>
</html>
Do you mean something like:
$(document).on("click", "#firstTable tr button", function(b) {
b = $(this).closest("tr");
var d = $.trim(b.find("td:first").text());
b = parseFloat($.trim(b.find("td:nth-child(3)").text()));
var a = $("#secondTable"),
c = a.find("tr").filter(function(a) {
return $.trim($(this).find("td:first").text()) == d
});
c.length ? (a = c.find("td:nth-child(2)"), c = parseFloat($.trim(a.text())), a.text(b + c)) : (a = $("<tr />").appendTo(a), $("<td />", {
text: d
}).appendTo(a), $("<td />", {
text: b
}).appendTo(a))
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="firstTableDiv">
<table border="1" id="firstTable">
<thead>
<tr>
<th>Item</th>
<th>Stock</th>
<th colspan="1">Sold</th>
</tr>
</thead>
<tbody id="firstTableBody">
<tr>
<td>Apples</td>
<td>300</td>
<td>200</td>
<td><button>Sell</button></td>
</tr>
<tr>
<td>Apples</td>
<td>300</td>
<td>100</td>
<td><button>Sell</button></td>
</tr>
<tr>
<td>Oranges</td>
<td>400</td>
<td>300</td>
<td><button>Sell</button></td>
</tr>
</tbody>
</table>
</div>
<br />
<div id="secondTableDiv">
Sold
<table border="1" id="secondTable">
<thead>
<tr>
<th>Item</th>
<th>Sold</th>
</tr>
</thead>
<tbody id="secondTableBody"></tbody>
</table>
</div>

Adding a row that is writable in HTML

I have made a table that can add a row. But I want the row to be writable. When the user clicks the addRow a new row will appear and the user can input a text on it. Can someone help me to do it? Thankyou so much.
the code is in the jsFiddle.
jsFiddle
Here is the solution in jsFiddle
http://jsfiddle.net/96oqxz9z/
All you need to add is a simple line:
$('#tbl1').append("<TR><TD></TD><TD><input type=\"text\"></TD></TR>");
Try this
Check here
function addRow() {
$('#addmore').append('<tr><td><input type="text" value="1"></td><td><input type="text" value="2"></td></tr><tr><td> </td></tr>')
};
$(document).on('click', '#add', function() {
var row = '<tr><td><input type="text" /></td></tr>';
$(this).closest('table').append(row);
})
td {
border: 1px solid #ccc;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td id="add">add row </td>
</tr>
</table>
try using this:
function addRow() {
"use strict";
var table = document.getElementById("tbl1");
var row=table.insertRow(table.rows.length);
console.log(row);
var td1=row.insertCell(0);
var td11 = document.createElement("span");
td1.appendChild(td11);
var td2=row.insertCell(1);;
var td22 = document.createElement("input");
td22.type = "text";
td2.appendChild(td22);
td11.innerHTML = document.getElementById("a").innerHTML;
td2.value = document.getElementById("b").innerHTML;
row.appendChild(td1);
row.appendChild(td2);
table.children[0].appendChild(row);
}
<input type="button" onclick="addRow()" value="Add Row"/>
<TABLE id="tbl1">
<TR>
<TH></TH>
<TH id="a">Principal Name</TH>
<TH id="b">Principal Titles</TH>
</TR>
<TR>
<TD></TD>
<TD>Director Of Manager</TD>
</TR>
<TR>
<TD></TD>
<TD>President</TD>
</TR>
<TR>
<TD></TD>
<TD>Treasurer</TD>
</TR>
</TABLE>

Categories

Resources