Adding a row that is writable in HTML - javascript

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>

Related

make each table value display in each textbox

I have this html table and 2 textboxes:
<table id="myTbl">
<thead>
<tr>
<th>A</th>
<th>B</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>2</td>
</tr>
</tbody>
</table>
<input type="text" name="txt" id="txt" >
<input type="text" name="txt" id="txt2" >
I want when reload the page, the values 1 and 2 must display in each textbox. How can I do it?
I have tried this js code but wrong and I want it auto display, not to click it:
var cells = document.querySelectorAll('#myTbl tbody ');
Array.from(cells).forEach(function (elem) {
elem.addEventListener('click', function () {
document.getElementById('txt').value = this.textContent;
})
})
var tbody = document.getElementsByTagName('tbody')[0]
var input1 = document.getElementById('txt')
var input2 = document.getElementById('txt2')
input1.value = tbody.getElementsByTagName('td')[0].textContent
input2.value = tbody.getElementsByTagName('td')[1].textContent

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>

Counting values from td's in jQuery

I have a problem with jQuery script. I'm trying to make a simple counting loop, for each tr. I got a table like below, and I want to select the second td, multiply it by two and add to the third td and display the result in the fourth td.
https://codepen.io/adeowsky/pen/YEgVKG
I'm trying to make it with the for each loop like below ->
<script>
(function($) {
$('.sp-league-table tbody tr').each( function() {
var pct = this.find('.data-pct').text();
console.log(pct);
//var pct = $('').hasClass('data-pct').text();
//console.log(pct);
var winy = $('.data-w').text();
var losy = $('.data-l').text();
/*var pkt = (winy*2) + (losy*2);
$('.data-pct').text(pkt);*/
});
})( jQuery );
</script>
But it doesn't work for me, where is the reason?
You are selecting all the elements with the class, not the one in the current row.
var tr = $(this);
var pCell = tr.find(".data-pct")
var wCell = tr.find('.data-w')
var lCell = tr.find('.data-l')
There are a couple of problems
Your table does not have the required class
you're not targeting the specific row's cells
You should explicitly parse the string values to integers
you've commented out the bit that does the calculation:
$(function(){
$('.sp-league-table tbody tr').each( function() {
var pct = $('.data-pct',this).text();
var winy = parseInt($('.data-w',this).text(),10);
var losy =parseInt($('.data-l',this).text(),10);
var pkt = (winy*2) + (losy*2);
$('.data-pct',this).text(pkt);
});
})
Updated: https://codepen.io/anon/pen/NwJjaO
Live example:
$(function(){
$('.sp-league-table tbody tr').each( function() {
var pct = $('.data-pct',this).text();
var winy = parseInt($('.data-w',this).text(),10);
var losy =parseInt($('.data-l',this).text(),10);
var pkt = (winy*2) + (losy*2);
$('.data-pct',this).text(pkt);
});
})
table, tr, td, th {
border: 1px solid #000;
border-collapse: collapse;
padding: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="sp-league-table">
<thead>
<tr>
<th>Name</th>
<th>W</th>
<th>L</th>
<th>PCT</th>
</thead>
<tr>
<td>Name 1</td>
<td class="data-w">12</td>
<td class="data-l">0</td>
<td class="data-pct">x</td>
</tr>
<tr>
<td>Name 2</td>
<td class="data-w">9</td>
<td class="data-l">3</td>
<td class="data-pct">x</td>
</tr>
</table>
<table class="sp-league-table">
<thead>
<tr>
<th>Name</th>
<th>W</th>
<th>L</th>
<th>PCT</th>
</thead>
<tr>
<td>Name 1</td>
<td class="data-w">12</td>
<td class="data-l">0</td>
<td class="data-pct">24</td>
</tr>
<tr>
<td>Name 2</td>
<td class="data-w">6</td>
<td class="data-l">5</td>
<td class="data-pct">17</td>
</tr>
</table>

how to count table tbody tr using jquery

please suggest me
my code :
$('.Create-New-Order').click(function () {
var totalRowCount = $("#table_New_Order tbody tr").length;
alert(totalRowCount);
});
On-load table tr count
$(function() {
$('.Create-New-Order').click(function() {
var total = $('#mytbl tr').length ;
alert('tr count = '+ total);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<table border="1px solid red">
<tr>
<th>Name</th><th>Email</th>
</tr>
<tbody id="mytbl">
<tr>
<td>sfdsd</td><td>tsdaf#ymail.com</td>
</tr>
<tr>
<td>sfdsd</td><td>tsdaf#ymail.com</td>
</tr>
<tr>
<td>sfdsd</td><td>tsdaf#ymail.com</td>
</tr>
</tbody>
</table>
<br>
<br>
Create-New-Order

Loop HTML table and add the identical items and its calculated amount to another table

<html>
<body>
<div>
<table border="1" id="topTable">
<thead>
<th>Item</th>
<th>Sold</th>
</thead>
<tbody id="topTableBody">
<tr>
<td>Apples</td>
<td>50</td>
</tr>
<tr>
<td>Apples</td>
<td>25</td>
</tr>
<tr>
<td>Oranges</td>
<td>30</td>
</tr>
<tr>
<td>Strawberry</td>
<td>60</td>
</tr>
<tr>
<td>Cherry</td>
<td>10</td>
</tr>
<tr>
<td>Guava</td>
<td>5</td>
</tr>
<tr>
<td>Strawberry</td>
<td>20</td>
</tr>
</tbody>
</table>
</div>
<button id="btn">Click</button>
</br>
<div>
<table border="1" id="bottomTable">
<thead>
<th>Item</th>
<th>Sold</th>
</thead>
<tbody id="bottomTableBody">
</tbody>
</table>
</div>
</body>
</html>
When I press on the button I want it to loop through the top table and get the item names that're alike and add them in one row with the sold amount combined in the bottom table ex: apples will have their own row with a sold amount of 75 and others who have no names that're alike will have their own row such as Oranges with the sold amount also.
If you can use JQuery.
(JSFiddle: http://jsfiddle.net/inanda/o9axgkaz/):
jQuery('#btn').on('click', function() {
var sumMap = {};
//Iterate through table rows
$("table tbody tr").each(function () {
if (sumMap[$(this).children('td:nth-child(1)').text()]) {
sumMap[$(this).children('td:nth-child(1)').text()] = sumMap[$(this).children('td:nth-child(1)').text()] +Number($(this).children('td:nth-child(2)').text());
} else {
sumMap[$(this).children('td:nth-child(1)').text()] = Number($(this).children('td:nth-child(2)').text());
}
})
//Append result to the other table
$.each(sumMap, function (i, val) {
$('#bottomTable tr:last').after('<tr><td>'+i+'</td><td>'+val+'</td>');
});
});
Pure javascript:
(JSFiddle: http://jsfiddle.net/inanda/2dmwudfj/ ):
appendResultToBottomTable= function() {
var sumMap = calculate();
appendResultToTable('bottomTableBody', sumMap);
}
function calculate() {
var table = document.getElementById("topTableBody");
var map = {};
for (var i = 0, row; row = table.rows[i]; i++) {
var itemType=(row.cells[0].innerText || row.cells[0].textContent);
var value=(row.cells[1].innerText || row.cells[1].textContent);
if (map[itemType]) {
map[itemType] = map[itemType] +Number(value);
} else {
map[itemType] = Number(value);
}
}
return map;
}
function appendResultToTable(tableId, sumMap){
var table = document.getElementById(tableId);
for (var item in sumMap){
var row = table.insertRow(table.rows.length);
var cellItem = row.insertCell(0);
var cellValue = row.insertCell(1);
cellItem.appendChild(document.createTextNode(item));
cellValue.appendChild(document.createTextNode(sumMap[item]));
}
}
If it is applicable for your project to use external libraries, you can do it with code like below:
alasql('SELECT Item,SUM(CONVERT(INT,Sold)) AS Sold \
INTO HTML("#res",{headers:true}) \
FROM HTML("#topTable",{headers:true}) \
GROUP BY Item');
Here:
SELECT Item, SUM(Sold) FROM data GROUP BY Item is a regular SQL expression to group and sum data from the table
CONVERT(INT,Sold) conversion procedure from string to INT type
FROM HTML() and INTO HTML() special functions to read/write data from/to HTML table, {headers:true} is a parameter to use headers
I added some minor CSS code (for table and cells borders), because Alasql generates the "plain" HTML table.
See the working snippet below.
(Disclaimer: I am an author of Alasql library)
function run() {
alasql('SELECT Item,SUM(CONVERT(INT,Sold)) AS Sold INTO HTML("#res",{headers:true}) FROM HTML("#topTable",{headers:true}) GROUP BY Item');
}
#res table {
border:1px solid black;
}
#res table td, th{
border:1px solid black;
}
<script src="http://alasql.org/console/alasql.min.js"> </script>
<div>
<table border="1" id="topTable">
<thead>
<th>Item</th>
<th>Sold</th>
</thead>
<tbody id="topTableBody">
<tr>
<td>Apples</td>
<td>50</td>
</tr>
<tr>
<td>Apples</td>
<td>25</td>
</tr>
<tr>
<td>Oranges</td>
<td>30</td>
</tr>
<tr>
<td>Strawberry</td>
<td>60</td>
</tr>
<tr>
<td>Cherry</td>
<td>10</td>
</tr>
<tr>
<td>Guava</td>
<td>5</td>
</tr>
<tr>
<td>Strawberry</td>
<td>20</td>
</tr>
</tbody>
</table>
</div>
<button id="btn" onclick="run()">Click</button>
</br>
<div id="res"></div>

Categories

Resources