Copy Contents in Dynamic Generating Textboxes from Add Button - javascript

I have Add button and 6 columns. When I click on add button it generates row dynamically, and delete likewise. problem is I want to use 2 columns to copy the content of one textbox into another. I can do simply for fixed columns but how can I do this for dynamic textbox.
If i write 2 in Amount column and keyup tab, then 2 should come in Total Column. It should happen in every dynamic row.
Kindly tell.

I have done it using jQuery. Please have a look at it. Please check keyup event handler which works with dynamically added rows also. Hope it will help you.
function addRow(){
//for adding rows dynamically
var tableElement = document.getElementById("mytable");
var currentTrLength = tableElement.getElementsByTagName("tr").length;
var currentTrIndex = currentTrLength-1; //id are ending with _0, _1 and so on
var rowRef = tableElement.getElementsByTagName("tr")[1].cloneNode(true);
var amountTextElement = rowRef.getElementsByClassName("Amount")[0];
var totalTextElement = rowRef.getElementsByClassName("Total")[0];
amountTextElement.id = "Amount_"+currentTrIndex;
totalTextElement.id = "Amount_"+currentTrIndex;
amountTextElement.value = "";
totalTextElement.value = "";
document.getElementById("mytable").appendChild(rowRef)
}
function copy(obj){
var current = obj;
var currentTr = current.parentElement.parentElement;
var currentTotalElem = currentTr.getElementsByClassName("Total")[0];
currentTotalElem.value = current.value;
}
function calculatesum(){
}
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
th, td {
padding: 5px;
}
<button class="addRow" onclick="addRow()">Add Row</button>
<br/><br/>
<table id="mytable" style="width:90%">
<tr>
<th>Column1</th>
<th>Column2</th>
<th>Column3</th>
<th>Column4</th>
<th>Amount</th>
<th>Total</th>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>94</td>
<td>Test</td>
<td><input name='Amount[]' class='form-control Amount' style='width:180px' type='text' onblur='calculatesum();' onkeyup='copy(this);' id='Amount_0' size='10' /></td>
<td><input name='Total[]' style='width:180px' class='form-control Total' type='text' id='Total_0' size='10' /></td>
</tr>
</table>
</body>
</html>

Have a look at below code:
in your <td> code you have call to copy() on onblur event as onkeyup='calculatesum();' onblur='copy(this);' I have passed current element's reference by this
var cc = 1;
function addTableRow(jQtable){
var id=cc;
jQtable.each(function() {
var data = "<tr><td class='Arial_4C8966'><input name='Amount[]' class='form-control Amount[]' style='width:180px' type='text' onkeyup='calculatesum();' onblur='copy(this);' id='Amount_" + cc + "' size='10' /></td><td class='Arial_4C8966'><input name='Total[]' style='width:180px' class='form-control Total' type='text' id='Total_" + cc + "' size='10' /></td></tr>";
var $table = $(this);
var n = $('tr:last td', this).length;
var tds = data;
cc++;
if ($('tbody', this).length > 0)
{
$('tbody', this).append(tds);
}
else
{
$(this).append(tds);
}
});
}
function copy(obj){
var current = obj;
var currentTr = current.parentElement.parentElement;
var currentTotalElem = currentTr.getElementsByClassName("Total")[0];
currentTotalElem.value = current.value;
}
function calculatesum(){
}
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
th, td {
padding: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<div class="row clearfix"> <div class="col-md-12 column">
<table class="table table-bordered table-hover" id="dynamicInput">
<tr class="Form_Text_Label">
<td align="center" >AMOUNT*</td>
<td align="center" >TOTAL*</td>
</tr>
</table>
</div>
<fieldset style="width:95%;">
<div>
<div class="col-sm-6">
<input type="button" value="Add" class="frmBtns" onClick="addTableRow($('#dynamicInput'));" style="font-family:Calibri; font-size:15px; " > <br>
</div>
</div>
</fieldset>

Related

How to show JSON response in datatable using JavaScript [duplicate]

I have an HTML table with a header and a footer:
<table id="myTable">
<thead>
<tr>
<th>My Header</th>
</tr>
</thead>
<tbody>
<tr>
<td>aaaaa</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>My footer</td>
</tr>
<tfoot>
</table>
I am trying to add a row in tbody with the following:
myTable.insertRow(myTable.rows.length - 1);
but the row is added in the tfoot section.
How do I insert tbody?
If you want to add a row into the tbody, get a reference to it and call its insertRow method.
var tbodyRef = document.getElementById('myTable').getElementsByTagName('tbody')[0];
// Insert a row at the end of table
var newRow = tbodyRef.insertRow();
// Insert a cell at the end of the row
var newCell = newRow.insertCell();
// Append a text node to the cell
var newText = document.createTextNode('new row');
newCell.appendChild(newText);
<table id="myTable">
<thead>
<tr>
<th>My Header</th>
</tr>
</thead>
<tbody>
<tr>
<td>initial row</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>My Footer</td>
</tr>
</tfoot>
</table>
(old demo on JSFiddle)
You can try the following snippet using jQuery:
$(table).find('tbody').append("<tr><td>aaaa</td></tr>");
Basic approach:
This should add HTML-formatted content and show the newly added row.
var myHtmlContent = "<h3>hello</h3>"
var tableRef = document.getElementById('myTable').getElementsByTagName('tbody')[0];
var newRow = tableRef.insertRow(tableRef.rows.length);
newRow.innerHTML = myHtmlContent;
I think this script is what exactly you need
var t = document.getElementById('myTable');
var r =document.createElement('TR');
t.tBodies[0].appendChild(r)
You're close. Just add the row to the tbody instead of table:
myTbody.insertRow();
Just get a reference to tBody (myTbody) before use. Notice that you don't need to pass the last position in a table; it's automatically positioned at the end when omitting argument.
A live demo is at jsFiddle.
Add rows:
<html>
<script>
function addRow() {
var table = document.getElementById('myTable');
//var row = document.getElementById("myTable");
var x = table.insertRow(0);
var e = table.rows.length-1;
var l = table.rows[e].cells.length;
//x.innerHTML = " ";
for (var c=0, m=l; c < m; c++) {
table.rows[0].insertCell(c);
table.rows[0].cells[c].innerHTML = " ";
}
}
function addColumn() {
var table = document.getElementById('myTable');
for (var r = 0, n = table.rows.length; r < n; r++) {
table.rows[r].insertCell(0);
table.rows[r].cells[0].innerHTML = " ";
}
}
function deleteRow() {
document.getElementById("myTable").deleteRow(0);
}
function deleteColumn() {
// var row = document.getElementById("myRow");
var table = document.getElementById('myTable');
for (var r = 0, n = table.rows.length; r < n; r++) {
table.rows[r].deleteCell(0); // var table handle
}
}
</script>
<body>
<input type="button" value="row +" onClick="addRow()" border=0 style='cursor:hand'>
<input type="button" value="row -" onClick='deleteRow()' border=0 style='cursor:hand'>
<input type="button" value="column +" onClick="addColumn()" border=0 style='cursor:hand'>
<input type="button" value="column -" onClick='deleteColumn()' border=0 style='cursor:hand'>
<table id='myTable' border=1 cellpadding=0 cellspacing=0>
<tr id='myRow'>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
</tr>
</table>
</body>
</html>
And cells.
let myTable = document.getElementById('myTable').getElementsByTagName('tbody')[0];
let row = myTable.insertRow();
let cell1 = row.insertCell(0);
let cell2 = row.insertCell(1);
let cell3 = row.insertCell(2);
cell1.innerHTML = 1;
cell2.innerHTML = 'JAHID';
cell3.innerHTML = 23;
row = myTable.insertRow();
cell1 = row.insertCell(0);
cell2 = row.insertCell(1);
cell3 = row.insertCell(2);
cell1.innerHTML = 2;
cell2.innerHTML = 'HOSSAIIN';
cell3.innerHTML = 50;
table {
border-collapse: collapse;
}
td, th {
border: 1px solid #000;
padding: 10px;
}
<table id="myTable">
<thead>
<tr>
<th>ID</th>
<th>NAME</th>
<th>AGE</th>
</tr>
</thead>
<tbody></tbody>
</table>
Add Column, Add Row, Delete Column, Delete Row. Simplest way
function addColumn(myTable) {
var table = document.getElementById(myTable);
var row = table.getElementsByTagName('tr');
for(i=0;i<row.length;i++){
row[i].innerHTML = row[i].innerHTML + '<td></td>';
}
}
function deleterow(tblId)
{
var table = document.getElementById(tblId);
var row = table.getElementsByTagName('tr');
if(row.length!='1'){
row[row.length - 1].outerHTML='';
}
}
function deleteColumn(tblId)
{
var allRows = document.getElementById(tblId).rows;
for (var i=0; i<allRows.length; i++) {
if (allRows[i].cells.length > 1) {
allRows[i].deleteCell(-1);
}
}
}
function myFunction(myTable) {
var table = document.getElementById(myTable);
var row = table.getElementsByTagName('tr');
var row = row[row.length-1].outerHTML;
table.innerHTML = table.innerHTML + row;
var row = table.getElementsByTagName('tr');
var row = row[row.length-1].getElementsByTagName('td');
for(i=0;i<row.length;i++){
row[i].innerHTML = '';
}
}
table, td {
border: 1px solid black;
border-collapse:collapse;
}
td {
cursor:text;
padding:10px;
}
td:empty:after{
content:"Type here...";
color:#cccccc;
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form>
<p>
<input type="button" value="+Column" onclick="addColumn('tblSample')">
<input type="button" value="-Column" onclick="deleteColumn('tblSample')">
<input type="button" value="+Row" onclick="myFunction('tblSample')">
<input type="button" value="-Row" onclick="deleterow('tblSample')">
</p>
<table id="tblSample" contenteditable><tr><td></td></tr></table>
</form>
</body>
</html>
You can also use querySelector to select the tbody, then insert a new row at the end of it.
Use append to insert Node or DOMString objects to a new cell, which will then be inserted into the new row.
var myTbody = document.querySelector("#myTable>tbody");
var newRow = myTbody.insertRow();
newRow.insertCell().append("New data");
<table id="myTable">
<thead>
<tr>
<th>My Header</th>
</tr>
</thead>
<tbody>
<tr>
<td>Data</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>My footer</td>
</tr>
</tfoot>
</table>
I have tried this, and this is working for me:
var table = document.getElementById("myTable");
var row = table.insertRow(myTable.rows.length-2);
var cell1 = row.insertCell(0);
You can use the following example:
<table id="purches">
<thead>
<tr>
<th>ID</th>
<th>Transaction Date</th>
<th>Category</th>
<th>Transaction Amount</th>
<th>Offer</th>
</tr>
</thead>
<!-- <tr th:each="person: ${list}" >
<td><li th:each="person: ${list}" th:text="|${person.description}|"></li></td>
<td><li th:each="person: ${list}" th:text="|${person.price}|"></li></td>
<td><li th:each="person: ${list}" th:text="|${person.available}|"></li></td>
<td><li th:each="person: ${list}" th:text="|${person.from}|"></li></td>
</tr>
-->
<tbody id="feedback">
</tbody>
</table>
JavaScript file:
$.ajax({
type: "POST",
contentType: "application/json",
url: "/search",
data: JSON.stringify(search),
dataType: 'json',
cache: false,
timeout: 600000,
success: function (data) {
// var json = "<h4>Ajax Response</h4><pre>" + JSON.stringify(data, null, 4) + "</pre>";
// $('#feedback').html(json);
//
console.log("SUCCESS: ", data);
//$("#btn-search").prop("disabled", false);
for (var i = 0; i < data.length; i++) {
//$("#feedback").append('<tr><td>' + data[i].accountNumber + '</td><td>' + data[i].category + '</td><td>' + data[i].ssn + '</td></tr>');
$('#feedback').append('<tr><td>' + data[i].accountNumber + '</td><td>' + data[i].category + '</td><td>' + data[i].ssn + '</td><td>' + data[i].ssn + '</td><td>' + data[i].ssn + '</td></tr>');
alert(data[i].accountNumber)
}
},
error: function (e) {
var json = "<h4>Ajax Response</h4><pre>" + e.responseText + "</pre>";
$('#feedback').html(json);
console.log("ERROR: ", e);
$("#btn-search").prop("disabled", false);
}
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="stylesheet" type="text/css" href="css/style.css" />
<title>Expense Tracker</title>
</head>
<body>
<h1>Expense Tracker</h1>
<div id="myDiv">
<label for="name">Name:</label>
<input
type="text"
name="myInput"
id="myInput"
placeholder="Name of expense"
size="50"
/><br /><br />
<label for="date">Date:</label>
<input type="date" id="myDate" name="myDate" />
<label for="amount">Amount:</label>
<input
type="text"
name="myAmount"
id="myAmount"
placeholder="Dollar amount ($)"
/><br /><br />
<span onclick="addRow()" class="addBtn">Add Expense</span>
</div>
<br />
<input type="button" value="Add Rows" onclick="addRows()" />
<!-- Optional position -->
<table id="myTable">
<tr>
<th>Name</th>
<th>Date</th>
<th>Amount</th>
<th>Delete</th>
</tr>
<tr>
<td>McDonald's</td>
<td>6/22/2017</td>
<td>$12.00</td>
<td>
<input type="button" value="Delete" onclick="deleteRow(this)" />
</td>
</tr>
</table>
<script>
function deleteRow(r) {
var i = r.parentNode.parentNode.rowIndex;
document.getElementById("myTable").deleteRow(i);
}
function addRows() {
console.log("add rows");
document.getElementById("myTable").innerHTML += `<tr>
<td>McDonald's</td>
<td>6/22/2017</td>
<td>$12.00</td>
<td>
<input type="button" value="Delete" onclick="deleteRow(this)" />
</td>
</tr>`;
}
</script>
</body>
</html>
$("#myTable tbody").append(tablerow);

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 check if all textboxes in a row are filled using jquery

I have 3 textboxes in each row. At least one of the rows should be filled completely. All the textboxes in any of the rows should not be empty. I have tried below code, it's for the first row only.
var filledtextboxes= $(".setup_series_form tr:first input:text").filter(function () {
return $.trim($(this).val()) != '';
}).length;
We want to get the maximum number of non-empty textboxes in any row, TIA.
Loop through all the rows. In each row, get the number of filled boxes. If this is higher than the previous maximum, replace the maximum with this count.
var maxboxes = -1;
var maxrow;
$(".setup_series_form tr").each(function(i) {
var filledtextboxes = $(this).find("input:text").filter(function () {
return $.trim($(this).val()) != '';
}).length;
if (filledtextboxes > maxboxes) {
maxboxes = filledtextboxes;
maxrow = i;
}
});
You are targeting only first tr here $(".setup_series_form tr:first input:text") so you will not get the expected output.
You have to iterate with every row(tr) inside form and then find the count of
text field having not empty values and store in a maxCount variable by comparing it previous tr count.
Here is a working snippet:
$(document).ready(function() {
var maxCountInRow =0;
var rowNumber;
$(".setup_series_form tr").each(function(index){
var filledtextboxes= $(this).find("input:text").filter(function () {
return $.trim($(this).val()) != '';
}).length;
if(filledtextboxes>maxCountInRow){
maxCountInRow=filledtextboxes;
rowNumber=index;
}
});
console.log("Row Number:"+rowNumber+" having maxCount: "+maxCountInRow);
});
.registrant_table{width: 100%;border: 1px solid #ccc;text-align: center;}
.registrant_table tr td{border: 1px solid #ccc;height: 42px;font-weight: bolder;}
.registrant_table input{border: 0px !important;width: 100%;height: 42px;text-align: center;font-weight: normal;}
label.error{color: red !important;}
.err-fields{background-color:red;color: white !important;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="setup_series_form">
<div>
<table class="registrant_table">
<tr class="title">
<td>No</td>
<td>Official Full Name</td>
<td>Mobile Contact</td>
<td>Email</td>
</tr>
<tr class="in-fields">
<td>1</td>
<td><input type="text" value="sas" name="firstname[]"></td>
<td><input type="text" value="" name="phone[]"></td>
<td><input type="text" value="" name="email[]"></td>
</tr>
<tr class="in-fields">
<td>2</td>
<td><input type="text" value="sas" name="firstname[]"></td>
<td><input type="text" value="sas" name="phone[]"></td>
<td><input type="text" name="email[]"></td>
</tr>
<tr class="in-fields">
<td>3</td>
<td><input type="text" name="firstname[]"></td>
<td><input type="text" name="phone[]"></td>
<td><input type="text" name="email[]"></td>
</tr>
</table>
</div>
</form>

How jQuery invoices form and delete how buttons add

I am currently working on a dynamic invoice system for myself. But I can't make it work correctly.
I want to add a delete button to this form but I cannot do so.
I have an invoice table like this in HTML:
$('#addRow').click(function () {
addItem();
});
$('#items_table').on('keyup', '.update', function () {
var key = event.keyCode || event.charCode; // if the user hit del or backspace, dont do anything
if( key == 8 || key == 46 ) return false;
calculateTotals();
});
$('#taxPercentage').change(function () {
calculateTotals(); // user changed tax percentage, recalculate everything
});
function calculateTotals(){
// get all of the various input typs from the rows
// each will be any array of elements
var nameElements = $('.row-name');
var quantityElements = $('.row-quantity');
var taxElements = $('.row-tax');
var priceElements = $('.row-price');
var totalElements = $('.row-total');
// get the bottom table elements
var taxPercentageElement =$('#taxPercentage');
var subTotalElement =$('#subTotal');
var totalTaxElement =$('#totalTax');
var grandTotalElement =$('#grandTotal');
var subTotal=0;
var taxTotal=0;
var grandTotal=0;
$(quantityElements).each(function(i,e){
// get all the elements for the current row
var nameElement = $('.row-name:eq(' + i + ')');
var quantityElement = $('.row-quantity:eq(' + i + ')');
var taxElement = $('.row-tax:eq(' + i + ')');
var priceElement = $('.row-price:eq(' + i + ')');
var totalElement = $('.row-total:eq(' + i + ')');
// get the needed values from this row
var qty = quantityElement.val().trim().replace(/[^0-9$.,]/g, ''); // filter out non digits like letters
qty = qty == '' ? 0 : qty; // if blank default to 0
quantityElement.val(qty); // set the value back, in case we had to remove soemthing
var price = priceElement.val().trim().replace(/[^0-9$.,]/g, '');
price = price == '' ? 0 : price; // if blank default to 0
priceElement.val(price); // set the value back, in case we had to remove soemthing
// get/set row tax and total
// also add to our totals for later
var rowPrice = (price * 1000) * qty
subTotal = subTotal + rowPrice;
var tax = taxPercentageElement.val() * rowPrice;
taxElement.val((tax / 1000).toFixed(2));
taxTotal = taxTotal + tax;
var total = rowPrice + tax
totalElement.val((total / 1000).toFixed(2));
grandTotal = grandTotal + total;
});
// set the bottom table values
subTotalElement.val((subTotal / 1000).toFixed(2));
totalTaxElement.val((taxTotal / 1000).toFixed(2));
grandTotalElement.val((grandTotal / 1000).toFixed(2));
}
function addItem() {
var itemRow =
'<tr>' +
'<td><input type="text" class="form-control row-name" placeholder="Item name" /></td>' +
'<td><input type="text" class="form-control update row-quantity" placeholder="Quantity" /></td>' +
'<td><input type="text" class="form-control update row-tax" placeholder="Tax" /></td>' +
'<td><input type="text" class="form-control update row-price" placeholder="Price" /></td>' +
'<td><input type="text" class="form-control row-total" disabled placeholder="0,00" /></td>' +
'</tr>';
$("#items_table").append(itemRow);
}
addItem(); //call function on load to add the first item
button{
font-size:18px;
}
.myTable {
background-color:#ffaa56;
}
.myTable {
border-collapse: collapse;
border-spacing: 0;
width:100%;
height:100%;
margin:0px;
padding:0px;
}
.myTable tr:last-child td:last-child {
-moz-border-radius-bottomright:0px;
-webkit-border-bottom-right-radius:0px;
border-bottom-right-radius:0px;
}
.myTable tr:first-child td:first-child {
-moz-border-radius-topleft:0px;
-webkit-border-top-left-radius:0px;
border-top-left-radius:0px;
}
.myTable tr:first-child td:last-child {
-moz-border-radius-topright:0px;
-webkit-border-top-right-radius:0px;
border-top-right-radius:0px;
}
.myTable tr:last-child td:first-child {
-moz-border-radius-bottomleft:0px;
-webkit-border-bottom-left-radius:0px;
border-bottom-left-radius:0px;
}
.myTable tr:hover td {
}
#items_table tr:nth-child(odd) {
background-color:#ffffff;
}
#items_table tr:nth-child(even) {
background-color:#ffd0a3;
}
.myTable td {
vertical-align:middle;
border:1px solid #000000;
border-width:0px 1px 1px 0px;
text-align:left;
padding:7px;
font-size:10px;
font-family:Arial;
font-weight:normal;
color:#000000;
}
.myTable tr:last-child td {
border-width:0px 1px 0px 0px;
}
.myTable tr td:last-child {
border-width:0px 0px 1px 0px;
}
.myTable tr:last-child td:last-child {
border-width:0px 0px 0px 0px;
}
html page
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<button id="addRow">Add a row</button><br><br>
<table class="myTable">
<thead>
<tr>
<th>Item Name</th>
<th>Quantity</th>
<th>Tax</th>
<th>Price</th>
<th>Total</th>
</tr>
</thead>
<tbody id="items_table"></tbody>
<tfoot>
<tr>
<th>Item Name</th>
<th>Quantity</th>
<th>Tax</th>
<th>Price</th>
<th>Total</th>
</tr>
</tfoot>
</table>
<br>
<br>
<table class="myTable" style="width:70%">
<thead>
<tr>
<th>Tax Percentage</th>
<th>Sub Total</th>
<th>Total Tax</th>
<th>Grand Total</th>
</tr>
</thead>
<tbody id="items_table">
<tr>
<td>
<select name="" id="taxPercentage" class="form-control">
<option value=".10">10%</option>
<option value=".15">15%</option>
</select>
<td><input type="text" class="form-control" id="subTotal" disabled placeholder="0,00" /></td>
<td><input type="text" class="form-control" id="totalTax" disabled placeholder="0,00" /></td>
<td><input type="text" class="form-control" id="grandTotal" disabled placeholder="0,00" /></td>
</tr>
</tbody>
<tfoot>
</tfoot>
</table>
I am currently out of ideas on how to do this correctly. So, all I need is once I filled 1 item row, the tax gets in the total table added, and once I change that tax in that row, it changes below as well, and the price has to be changed as well.
Can someone set me on the right track?
I want to add delete button to this form but I can not do it
The key here is to understand that event handlers usually can be set only on the elements that are present on the page at the moment of setting. Your code failed because you add rows dynamically - they didn't exist when you tried to assign an event handler. However, jQuery provides us with the special form of on() function that covers what we need in this case:
$('already present parent element selector').on("click", "existing/added later element selector", function () {
//code
});
So, in order to sort out your problem your code should look like this:
$('body').on("click", "#delRow", function () {
delItem($(this));
});
function delItem(elem) {
elem.parents("tr").remove();
calculateTotals();
}
Note that you have to add #delRow button to your template in addItem() function and corresponding <th> cells in the markup.
Regarding the whole thing, I would also make the tax cell disabled because it wouldn't make sense if users could edit it since the tax sum is defined by percent value below (either 10% or 15%). And the taxes are usually imposed by the govs. and known in advance. I mean you cannot just pay 5.745632% instead of 15% defined by a law.
Also I spotted one minor issue: when I remove symbols in the price cell the update doesn't get executed and the related cells' values don't change accordingly. You might want to read about input event on MDN.
In general it works fine if I understood your ideas correctly:
$('#addRow').on("click", function () {
addItem();
});
$('body').on("click", "#delRow", function () {
delItem($(this));
});
$('#items_table').on('input', '.update', function () {
var key = event.keyCode || event.charCode; // if the user hit del or backspace, dont do anything
if( key == 8 || key == 46 ) return false;
calculateTotals();
});
$('#taxPercentage').change(function () {
calculateTotals(); // user changed tax percentage, recalculate everything
});
function calculateTotals(){
// get all of the various input typs from the rows
// each will be any array of elements
var nameElements = $('.row-name');
var quantityElements = $('.row-quantity');
var taxElements = $('.row-tax');
var priceElements = $('.row-price');
var totalElements = $('.row-total');
// get the bottom table elements
var taxPercentageElement =$('#taxPercentage');
var subTotalElement =$('#subTotal');
var totalTaxElement =$('#totalTax');
var grandTotalElement =$('#grandTotal');
var subTotal=0;
var taxTotal=0;
var grandTotal=0;
$(quantityElements).each(function(i,e){
// get all the elements for the current row
var nameElement = $('.row-name:eq(' + i + ')');
var quantityElement = $('.row-quantity:eq(' + i + ')');
var taxElement = $('.row-tax:eq(' + i + ')');
var priceElement = $('.row-price:eq(' + i + ')');
var totalElement = $('.row-total:eq(' + i + ')');
// get the needed values from this row
var qty = quantityElement.val().trim().replace(/[^0-9$.,]/g, ''); // filter out non digits like letters
qty = qty == '' ? 0 : qty; // if blank default to 0
quantityElement.val(qty); // set the value back, in case we had to remove soemthing
var price = priceElement.val().trim().replace(/[^0-9$.,]/g, '');
price = price == '' ? 0 : price; // if blank default to 0
priceElement.val(price); // set the value back, in case we had to remove soemthing
// get/set row tax and total
// also add to our totals for later
var rowPrice = (price * 1000) * qty
subTotal = subTotal + rowPrice;
var tax = taxPercentageElement.val() * rowPrice;
taxElement.val((tax / 1000).toFixed(2));
taxTotal = taxTotal + tax;
var total = rowPrice + tax
totalElement.val((total / 1000).toFixed(2));
grandTotal = grandTotal + total;
});
// set the bottom table values
subTotalElement.val((subTotal / 1000).toFixed(2));
totalTaxElement.val((taxTotal / 1000).toFixed(2));
grandTotalElement.val((grandTotal / 1000).toFixed(2));
}
function delItem(elem) {
elem.parents("tr").remove();
calculateTotals();
}
function addItem() {
var itemRow =
'<tr>' +
'<td><button id="delRow">Delete</button></td><td><input type="text" class="form-control row-name" placeholder="Item name" /></td>' +
'<td><input type="text" class="form-control update row-quantity" placeholder="Quantity" /></td>' +
'<td><input type="text" disabled class="form-control update row-tax" placeholder="Tax" /></td>' +
'<td><input type="text" class="form-control update row-price" placeholder="Price" /></td>' +
'<td><input type="text" class="form-control row-total" disabled placeholder="0,00" /></td>' +
'</tr>';
$("#items_table").append(itemRow);
}
addItem(); //call function on load to add the first item
button{
font-size:18px;
}
.myTable {
background-color:#ffaa56;
}
.myTable {
border-collapse: collapse;
border-spacing: 0;
width:100%;
height:100%;
margin:0px;
padding:0px;
}
.myTable tr:last-child td:last-child {
-moz-border-radius-bottomright:0px;
-webkit-border-bottom-right-radius:0px;
border-bottom-right-radius:0px;
}
.myTable tr:first-child td:first-child {
-moz-border-radius-topleft:0px;
-webkit-border-top-left-radius:0px;
border-top-left-radius:0px;
}
.myTable tr:first-child td:last-child {
-moz-border-radius-topright:0px;
-webkit-border-top-right-radius:0px;
border-top-right-radius:0px;
}
.myTable tr:last-child td:first-child {
-moz-border-radius-bottomleft:0px;
-webkit-border-bottom-left-radius:0px;
border-bottom-left-radius:0px;
}
.myTable tr:hover td {
}
#items_table tr:nth-child(odd) {
background-color:#ffffff;
}
#items_table tr:nth-child(even) {
background-color:#ffd0a3;
}
.myTable td {
vertical-align:middle;
border:1px solid #000000;
border-width:0px 1px 1px 0px;
text-align:left;
padding:7px;
font-size:10px;
font-family:Arial;
font-weight:normal;
color:#000000;
}
.myTable tr:last-child td {
border-width:0px 1px 0px 0px;
}
.myTable tr td:last-child {
border-width:0px 0px 1px 0px;
}
.myTable tr:last-child td:last-child {
border-width:0px 0px 0px 0px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="addRow">Add a row</button><br><br>
<table class="myTable">
<thead>
<tr><th>Delete</th>
<th>Item Name</th>
<th>Quantity</th>
<th>Tax</th>
<th>Price per unit</th>
<th>Total</th>
</tr>
</thead>
<tbody id="items_table"></tbody>
<tfoot>
<tr><th>Delete</th>
<th>Item Name</th>
<th>Quantity</th>
<th>Tax</th>
<th>Price per unit</th>
<th>Total</th>
</tr>
</tfoot>
</table>
<br>
<br>
<table class="myTable" style="width:70%">
<thead>
<tr>
<th>Tax Percentage</th>
<th>Sub Total</th>
<th>Total Tax</th>
<th>Grand Total</th>
</tr>
</thead>
<tbody id="items_table">
<tr>
<td>
<select name="" id="taxPercentage" class="form-control">
<option value=".10">10%</option>
<option value=".15">15%</option>
</select>
<td><input type="text" class="form-control" id="subTotal" disabled placeholder="0,00" /></td>
<td><input type="text" class="form-control" id="totalTax" disabled placeholder="0,00" /></td>
<td><input type="text" class="form-control" id="grandTotal" disabled placeholder="0,00" /></td>
</tr>
</tbody>
<tfoot>
</tfoot>
</table>
As for your additional question - you can choose a locale to treat numbers as money in your country's format. It can be done by toLocaleString():
var num1 = 145636,
num2 = 145636;
console.log(num1.toLocaleString('en-US', {style: 'currency', currency: 'USD'})); // US format - 145,636
console.log(num2.toLocaleString('en-IN', {style: 'currency', currency: 'INR'})); // Indian format - 1,45,636
How can I separate the numbers that I write to price into a comma?
sample:
1,500
1,456,36

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