How jQuery invoices form and delete how buttons add - javascript

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

Related

Is there anyway to show always rows modified in a FooTable

The system is made with php, mysql, javascript, jquery and what it does is show a list of products and the user chooses the amount and shows a total.
I want to make a function that when the user modifies the quantity of a row, the row is always displayed in the Table, no matter if they search for other products or change the page of the table
This is the code
<table class="table-striped footable-res footable metro-blue" data-page-size="36" data-filter="#filter" style="color: #666;" data-filter-exact-match="false" id="tb">
<thead>
<th width="5%">°</th>
<th width="40%">Producto</th>
<th width="15%">Precio</th>
<th width="15%">Cantidad</th>
<th width="15%">Total</th>
<tr></tr>
</thead>
<tbody>
<td colspan=5 data-value='Nombre de categoria'><b>Nombre de categoria</b></td><tr></tr>";
<td>Contador 1</td>";
<input type='text' name='seleccion1' value='IDPRODUCTO' style='visibility: hidden !important; height: 0 !important; width: 0 !important; padding: 0 !important;'>";
<td data-value='NOMBREPRODUCTO CATEGORIAID CATEGORIANOMBRE' data-type='text'>"PRODUCTONOMBRE"</td>";
<td><input type='text' class='precio' name='precioIDPRODUCTO' id='precio' value='PR' style='color: black; background: transparent; border: 0; text-align: center;' readonly></td>";
<td><input type='text' class='cantidad' name='cantidadIDPRODUCTO' id='cantidad' placeholder='0' placeholder='0' style='color: black;'></td>";
<td><input type='text' class='total' name='totalIDPRODUCTO' id='total' value='0' value='0' style='color: black;'></td>";
<tr></tr>
}
}
if (CONTADOR==0){
<td colspan='3'>No se han agregado productos aún.</td>";
}
echo "<input type='text' name='cod_bod' value='".$sel_bodega."' style='visibility: hidden !important; height: 0 !important; width: 0 !important; padding: 0 !important;'>";
}
?>
</tbody>
<tfoot>
<style>
.footable > tfoot > tr > th, .footable > tfoot > tr > td{ color: black; }
input[type=text]{ color: black; }
</style>
<td colspan="4" align="right">Subtotal</td>
<td><input type="text" class="subtotal" name="subtotal" id="subtotal" readonly placeholder="0"></td>
<tr></tr>
<td colspan="4" align="right">Descuento %<input type="text" id="discount" name="discount" class="discount" style="color: black; background: transparent; border: 0; text-align: center; width: 20px;" value="0"></td>
<td><input type="text" class="descuento" class="descuento" name="descuento" id="descuento" readonly placeholder="0"></td>
<tr></tr>
<td colspan="4" align="right">Total</td>
<td><input type="number" pattern="[0-9]{2}" min="50000" max="2000000" class="totales" id="totales" name="totales" readonly placeholder="0" ></td>
<tr>
<td colspan="5">
<div class="pagination pagination-centered"></div>
</td>
</tr>
</tfoot>
</table>
<script>
//data-toggle="true"
document.getElementById("tb").addEventListener("input", function(e) {
const parent = e.target.closest("tr");
const precio = parent.querySelector('[class=precio]').value;
const cantidad = parent.querySelector('[class=cantidad]').value;
const total = precio * cantidad;
parent.querySelector('[class=total]').value = total;
document.querySelector('[class=subtotal]').value = subtotal();
document.querySelector('[class=discount]').value = discount();
document.querySelector('[class=descuento]').value = dscto();
document.querySelector('[class=totales]').value = totalfinal();
});
function subtotal(){
var subtotal = 0;
for(var x=0;x<document.querySelectorAll(".total").length;x++){
subtotal += Number(document.querySelectorAll(".total")[x].value);
}
return subtotal;
}
function discount(){
var subtotal = Number(document.getElementById("subtotal").value);
var discount = 0;
if(subtotal > 150000 && subtotal < 299999){
discount = 3;
}
if(subtotal > 300000 && subtotal < 449999){
discount = 4;
}
if(subtotal > 450000){
discount = 5;
}
return discount;
}
function dscto(){
var subtotal = Number(document.getElementById("subtotal").value);
var descuento = 0;
if(subtotal > 150000 && subtotal < 299999){
descuento = subtotal * 0.03;
}
if(subtotal > 300000 && subtotal < 449999){
descuento = subtotal * 0.04;
}
if(subtotal > 450000){
descuento = subtotal * 0.05;
}
return descuento;
}
function totalfinal(){
var subtotal2 = Number(document.getElementById("subtotal").value);
var descuento2 = Number(document.getElementById("descuento").value);
var totales = subtotal2 - descuento2;
return totales;
}

add dynamic input field with unique id for counting

I am working on a code to calculate the total price of services.
Now if I add the hours (like 2) and add the price per hour (like 20) the code has to calculate the price that will become the subtotal. After that It calculate the "BTW" (tax) and add it to the subtotal for the total price.
What I would like is to add dynamic new input fields with a unique id so the code can calculate multiple services. So for each service you've got a total amount which all combined will be the subtotal. My code for now:
HTML
<table class="table-responsive table" id="table-diensten">
<thead>
<tr>
<th>Time</th>
<th>Service</th>
<th>amount</th>
<th>total</th>
<th>BTW</th>
</tr>
</thead>
<tbody class="table-body">
<tr class="table-row">
<td><input type="text" class="form-control" placeholder="time (in hours)" id="time" onchange="totalofferte()"></td>
<td><input type="text" class="form-control" placeholder="service"></td>
<td><input type="text" class="form-control" placeholder="Cost (per hour)" id="cost" onchange="totalofferte()"></td>
<td>€ <span id="total">0,00</span></td>
<td>21%</td>
</tr>
</tbody>
<tfoot>
<tr>
<td> </td>
<td> </td>
<td><strong>Subtotaal</strong></td>
<td>€ <span id="subtotal">0,00</span></td>
<td> </td>
</tr>
<tr>
<td> </td>
<td> </td>
<td>21% BTW</td>
<td>€ <span id="costbtw">0,00</span></td>
<td> </td>
</tr>
<tr>
<td> </td>
<td> </td>
<td class="table-total"><span class="total">Totaal</span></td>
<td class="table-total"><span class="total">€ <span id="totalofferte">0,00</span></span></td>
<td> </td>
</tr>
</tfoot>
</table>
<a href="#table-diensten" class="add-tablerow btn btn-default" >add new service</a>
JS
<script type="text/javascript">
function totalofferte() {
var cost = document.getElementById('cost').value;
var time = document.getElementById('time').value;
if (cost > 0 && time > 0) {
var total = cost * time;
if (total > 0) {
document.getElementById('total').innerHTML = total;
var subtotal = total;
if (subtotal > 0) {
document.getElementById('subtotal').innerHTML = subtotal;
var costbtw = subtotal / 100 * 21;
document.getElementById('costbtw').innerHTML = costbtw;
var totalofferte = subtotal + costbtw;
document.getElementById('totalofferte').innerHTML = totalofferte;
}
}
}
}
</script>
Edit:
Forgot my JQuery
$(".add-tablerow").click(function(){
$( ".table-body" ).append("<tr class='table-row'><td><input type='text' class='form-control' placeholder='Tijd'></td><td><input type='text' class='form-control' placeholder='Omschrijving'></td><td><input type='text' class='form-control' placeholder='Kosten'></td><td>€ 0,00</td><td>21%</td></tr>");
});
Using addNewRow method you can achieve the behaviour you are expecting
function addNewRow(){
var presentRows = $("#table-diensten > tbody > tr");
var newRowId = presentRows.length + 1;
$("#table-diensten").append(
'<tr id="' + newRowId + '">' +
'<td><input class="form-control" type="number" name="time_' + newRowId + '" id="time_' + newRowId + '"/></td>' +
'<td><input class="form-control" type="number" name="service_' + newRowId + '" id="service_' + newRowId + '"/></td>' +
'<td><input class="form-control" type="number" name="amount' + newRowId + '" id="amount' + newRowId + '"/></td>' +
'<td></td>' +
'<td></td>' +
'</tr>'
);
}
function totalofferte() {
var cost = document.getElementById('cost').value;
var time = document.getElementById('time').value;
if (cost > 0 && time > 0) {
var total = cost * time;
if (total > 0) {
document.getElementById('total').innerHTML = total;
var subtotal = total;
if (subtotal > 0) {
document.getElementById('subtotal').innerHTML = subtotal;
var costbtw = subtotal / 100 * 21;
document.getElementById('costbtw').innerHTML = costbtw;
var totalofferte = subtotal + costbtw;
document.getElementById('totalofferte').innerHTML = totalofferte;
}
}
}
}
.navigation {
width: 300px;
}
.mainmenu, .submenu {
list-style: none;
padding: 0;
margin: 0;
}
.mainmenu a {
display: block;
background-color: #CCC;
text-decoration: none;
padding: 10px;
color: #000;
}
.mainmenu li:hover a,
.mainmenu li.active a {
background-color: #C5C5C5;
}
.mainmenu li.active .submenu {
display: block;
max-height: 200px;
}
.submenu a {
background-color: #999;
}
.submenu a:hover {
background-color: #666;
}
.submenu {
overflow: hidden;
max-height: 0;
-webkit-transition: all 0.5s ease-out;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table-responsive table" id="table-diensten">
<thead>
<tr>
<th>Time</th>
<th>Service</th>
<th>amount</th>
<th>total</th>
<th>BTW</th>
</tr>
</thead>
<tbody class="table-body">
<tr class="table-row">
<td><input type="text" class="form-control" placeholder="time (in hours)" id="time" onchange="totalofferte()"></td>
<td><input type="text" class="form-control" placeholder="service"></td>
<td><input type="text" class="form-control" placeholder="Cost (per hour)" id="cost" onchange="totalofferte()"></td>
<td>€ <span id="total">0,00</span></td>
<td>21%</td>
</tr>
</tbody>
<tfoot>
<tr>
<td> </td>
<td> </td>
<td><strong>Subtotaal</strong></td>
<td>€ <span id="subtotal">0,00</span></td>
<td> </td>
</tr>
<tr>
<td> </td>
<td> </td>
<td>21% BTW</td>
<td>€ <span id="costbtw">0,00</span></td>
<td> </td>
</tr>
<tr>
<td> </td>
<td> </td>
<td class="table-total"><span class="total">Totaal</span></td>
<td class="table-total"><span class="total">€ <span id="totalofferte">0,00</span></span></td>
<td> </td>
</tr>
</tfoot>
</table>
add new service
its very simple. Frist create your element example:
var input = $("<input/>").attr({
name: 'EmailSend',
type: 'text',
value: true,
class: "YOURClass"
id: "YouRid"
});
Than append your crated input to your wish element. example: $( ".table-body" ).append(input)
Adding items in DOM through Javascript
In order to add new Items in your table with Native Javascript you will have to use one of the following
Element.insertAdjacentHTML()
Element.innerHTML
Node.appendChild()
If you want to use jQuery instead then you can try
.append()
.html()
Add custom attributes to DOM items
If you want to add a new attribute on a DOM element , you can do it with Native Javascript using the
element.setAttribute(name, value);
or with jQuery
.attr();
Loop through items
Now in order to "process" those new values each time , you need to iterate through all your inputs and carry your calculations. Iteration can be done in Native Javascript through the use of
Element.getElementsByTagName() If all inputs should be processed in your Table.
Document.getElementsByClassName() If you assign a specific class on each of your inputs and only those will be processed.
or if you want to use jQuery you could go on with
jQuery.each()

Changes in <td> input texts doesn't reflect in text-area while the Javascript function works fine

function table_to_text() {
var j;
var z = '';
var k = 4;
var article1 = new Array();
for (j = 1; j <= k; j++) {
article1[j] = document.getElementById("c" + j).value;
z = z + article1[j];
}
document.getElementById("batch_full").innerText = z;
}
function text_to_table() {
var batch_text = document.getElementById("batch_full").value;
var length_covered = 0;
var n = 4;
var article = new Array();
var temp;
var length;
for (var i = 1; i <= n; i++) {
article[i] = document.getElementById("c" + i);
length = article[i].getAttribute('maxlength');
temp = batch_text.substr(length_covered, length);
article[i].value = temp;
length_covered = Number(length_covered) + Number(length);
}
}
#batch_full {
height: 200px;
width: 500px;
}
table {
border-collapse: collapse;
}
table,
th,
td {
padding: 0px 10px 0px 10px;
}
td {
border: 1px solid black;
}
th {
text-align: left;
text-indent: -2.5%;
}
td>input {
resize: horizontal;
width: 100%;
}
<textarea id="batch_full" onchange="text_to_table()">Batch input here</textarea>
<table id="results_table" onchange="table_to_text()">
<tr>
<th>S.No</th>
<th>Account Number</th>
<th>First Name</th>
<th>Last Name</th>
</tr>
<tr>
<td><input type="text" maxlength="2" id="c1"></td>
<td><input type="text" maxlength="10" id="c2"></td>
<td><input type="text" maxlength="10" id="c3"></td>
<td><input type="text" maxlength="10" id="c4"></td>
</tr>
</table>
<input type="button" onclick="text_to_table()" value="Text to Table">
<input type="button" onclick="table_to_text()" value="Table to Text">
When I enter some text in the element, the changes are reflected in the table elements, but when I try to edit the text in the element, the changes are not reflected in the element.
Please help me in resolving this issue. I'm using Codepen to write this code.
There are no bugs in your code.For instant reflection of your data which you are entering in either Textarea or Table, replace "onchange" event with "oninput" event in the TextArea and table elements and, Since you are using codepen the "innerText" attribute will not be rendered instead use "value" attribute.
That should do the trick.
Change the innterText to innerHTML. Seems to work: http://codepen.io/anon/pen/gLvqMN

How to add and delete new row with new values each time using JavaScript?

I have been given a task to make 2 HTML pages, one with form where the user enter his/her contact information and another where the user's information are viewed in a table.
I just need to use these languages only (JavaScript, jquery, HTML, CSS ,bootstrap); no use of PHP/JSP, only client-side language
and no database should be used. Up until now I have done this much.
$(function()
{
$('#form').validate(
{
rules:
{
email:
{required:true,
email:true
},
gender:
{required:true
},
cont:{
required:true,
number:true}
}
})
});
function onsumit(){
localStorage.setItem("input0",1);
var ip=document.getElementById("name");
localStorage.setItem("input1", ip.value);
var ip2=document.getElementById("email");
localStorage.setItem("input2", ip2.value);
var ip3=document.getElementById("cont");
localStorage.setItem("input3", ip3.value);
var ip4=document.getElementById("gender");
localStorage.setItem("input4", ip4.value);
var ip5=document.getElementById("comment");
localStorage.setItem("input5", ip5.value);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.12.0/jquery.validate.min.js"
type="text/javascript"></script>
<div class="divmid text-center" id="divmid" >
<p id="head"></p>
<a> CONTACT FORM</a>
<form class="table-responsive" id="form" name="form" action="next.html" method="get" onsubmit="onsumit()" >
<table>
<tr>
<td>NAME:</td>
<td><input type="text" name="name" id="name"required>*<p id="p1"></p></td>
</tr>
<tr>
<td>Contcat no:</td>
<td><input type="text" size="10" name="cont" id="cont"required>*<p id="p2"></p></td>
</tr>
<tr>
<td>EMAIL:</td>
<td><input type="text" name="email" id="email"required>*<p id="p3"></p></td>
</tr>
<tr>
<td>Gender:</td>
<td><select id="gender" name="gender" required>
<option value="" >SELECT</option>
<option value="male">MALE</option>
<option value="female">FEMALE</option>
</select>*<p id="p4"></p></td>
</tr>
<tr>
<td>comments:</td>
<td> <textarea class="form-control" rows="5" id="comment" maxlength="100"></textarea>
</td>
</tr>
</table>
<label><input id="submit" type="submit" value="SUBMIT"></label>
</form>
</div>
now this is the second html page.
function load(){
var table = document.getElementById("tab2");
var rowCount = table.rows.length;
var colCount = table.rows[0].cells.length;
var validate_Noof_columns = (colCount - 1);
var row = table.insertRow(1);
for(var i=0; i < colCount; i++) {
var text = localStorage.getItem("input"+i);
var newcell = row.insertCell(i);
if(i == (colCount - 1)) {
newcell.innerHTML = "<INPUT type='button' value='X' id='work' onclick='removeLine(this)'/><INPUT type='button' value='&' onclick='removeRow(this)'/>"; break;
} else {
newcell.innerHTML = text;
}
}
function removeLine(lineItem) {
var row = lineItem.parentNode.parentNode;
row.parentNode.removeChild(row);
}
function removeRow(onclickTAG) {
// Iterate till we find TR tag.
while ( (onclickTAG = onclickTAG.parentElement) && onclickTAG.tagName != 'TR' );
onclickTAG.parentElement.removeChild(onclickTAG);
}
}
body {
font: 20px Montserrat, sans-serif;
line-height: 1.8;
color: black;
}
p {font-size: 16px;}
.margin {margin-bottom: 45px;}
.bg-1 {
background-color: #1abc9c; /* Green */
color: #ffffff;
}
.bg-2 {
background-color: #474e5d; /* Dark Blue */
color: #ffffff;
}
.bg-3 {
background-color: #ffffff; /* White */
color: #555555;
}
.bg-4 {
background-color: #2f2f2f; /* Black Gray */
color: #fff;
}
.container-fluid {
padding-top: 70px;
padding-bottom: 70px;
}
.navbar {
padding-top: 15px;
padding-bottom: 15px;
border: 0;
border-radius: 0;
margin-bottom: 0;
font-size: 12px;
letter-spacing: 5px;
}
.navbar-nav li a:hover {
color: #1abc9c !important;
}
#divmid {
margin:20px;
padding:20px;
border:3px solid red;
}
table{
text-align:left ;
}
th, td {
padding: 20px;
text-align:left;
}
textarea{
max-height:300px;
resize:none;
}
#div1{
text-align:center;
}
#tab2 {
text-align:left ;
border:2px solid red;
margin-left:auto;
margin-top:40px;
margin-bottom:200px;
}
#pick{
padding:100px;
}
<style>
table, td,th{
border: 1px solid black;
}
</style>
<body onload="load()">
<div id="div1">
<span id="div2">CONTACT LIST</span>
<table id="tab2">
<tr>
<th>S No.</th>
<th>NAME</th>
<th>CONTACT</th>
<th>EMAIL</th>
<th>GENDER</th>
<th>COMMENTS</th>
<th>EDIT</th>
</tr>
</table>
</div>
</body>
The problem is I need to create a row in second page each time a user input with the new values in the form, but what in have done, it only creating one row and always updating it with the new values. Though I have used Local storage but still I am stuck here.
The problem is in the line 6 of your code. The parameter 1 passed to the insertRow function instantiates the variable row with the first row of your table. This way, every time you use insertCell in the row variable it updates the value on this first row. I think switching to rowCount + 1 will do the job.
function load(){
var table = document.getElementById("tab2");
var rowCount = table.rows.length;
var colCount = table.rows[0].cells.length;
var validate_Noof_columns = (colCount - 1);
var row = table.insertRow(rowCount + 1);
for(var i=0; i < colCount; i++) {
var text = localStorage.getItem("input"+i);
var newcell = row.insertCell(i);
if(i == (colCount - 1)) {
newcell.innerHTML = "<INPUT type='button' value='X' id='work' onclick='removeLine(this)'/><INPUT type='button' value='&' onclick='removeRow(this)'/>"; break;
} else {
newcell.innerHTML = text;
}
}
function removeLine(lineItem) {
var row = lineItem.parentNode.parentNode;
row.parentNode.removeChild(row);
}
function removeRow(onclickTAG) {
// Iterate till we find TR tag.
while ( (onclickTAG = onclickTAG.parentElement) && onclickTAG.tagName != 'TR' );
onclickTAG.parentElement.removeChild(onclickTAG);
}
}
take a look at this code. I think it should be what you are looking for.
Everytime the form is submitted, I first get the value of the local storage and add the new entry as JSON.
On the other page, I get the local storage, transform the value to get an object from the JSON string and use that object to show the informations inside the table.
Hope this help!
First Page :
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
function onsumit() {
if (typeof(Storage) !== "undefined") {
// Exemple of str : {'d' : [{'name':'Mister A','cont':'1',email':'MisterA#test.com'},{'name':'Mister B','cont':'1','email':'MisterB#test.com'}]}
var str = localStorage.getItem("contactinformation");
var contactModel;
if (str !== '') {
contactModel = JSON.parse(str);
} else {
contactModel = {
d : []
};
}
contactModel.d[contactModel.d.length] = {
name:$('#name').val(),
cont:$('#cont').val(),
email:$('#email').val()
}
localStorage.setItem("contactinformation",JSON.stringify(contactModel));
return true;
} else {
// Sorry! No Web Storage support..
return false;
}
}
</script>
</head>
<body>
<div class="divmid text-center" id="divmid" >
<p id="head"></p>
<a>CONTACT FORM</a>
<form id="form" name="form" action="next.html" method="get" onsubmit="return onsumit();">
<table>
<tr>
<td>NAME:</td>
<td><input type="text" name="name" id="name">*</td>
</tr>
<tr>
<td>Contcat no:</td>
<td><input type="text" size="10" name="cont" id="cont">*</td>
</tr>
<tr>
<td>EMAIL:</td>
<td><input type="text" name="email" id="email">*</td>
</tr>
</table>
<input id="submit" type="submit" value="SUBMIT">
</form>
</div>
</body>
</html>
Second Page :
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
table, td,th{
border: 1px solid black;
}
</style>
</head>
<body>
<div id="div1">
<span id="div2">CONTACT LIST</span>
<table id="tab2">
<tr>
<th>NAME</th>
<th>CONTACT</th>
<th>EMAIL</th>
</tr>
</table>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready(function(){
if (typeof(Storage) !== "undefined") {
var str = localStorage.getItem("contactinformation");
var info = JSON.parse(str);
if (typeof(info.d) !== "undefined") {
for (var x=0;x<info.d.length;x++) {
$('#tab2').append('<tr><td>' + info.d[x].name + '</td><td>' + info.d[x].cont + '</td><td>' + info.d[x].email + '</td></tr>');
}
}
}
});
</script>
</body>
</html>

Copy Contents in Dynamic Generating Textboxes from Add Button

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>

Categories

Resources