jQuery invoice and HTML - javascript

I am currently working on a dynamic invoice system for myself. But I can't seem to completely get it working correctly.
I have a invoice table like this in HTML:
Product name -- Quantity -- Tax -- Price (without tax) -- total price
My HTML looks like this:
<td><input type="text" placeholder="Item name" class="form-control" /></td>
<td class="text-center"><input type="number" min="1" id="target" placeholder="Quantity" class="form-control quantity" /></td>
<td class="text-center"><input type="text" placeholder="TAX" class="form-control tax" /></td>
<td class="text-right"><input type="text" placeholder="Price" class="form-control" /></td>
<td class="text-right"><input type="text" disabled placeholder="0,00" class="form-control price" /></td>
I can add rows with this Javascript code:
<script>
function addItem(){
var itemRow =
'<tr>' +
'<td><input type="text" class="form-control" placeholder="Item name" /></td>' +
'<td><input type="text" class="form-control" placeholder="Quantity" /></td>' +
'<td><input type="text" class="form-control tax" placeholder="Tax" /></td>' +
'<td><input type="text" class="form-control" placeholder="Price" /></td>' +
'<td><input type="text" class="form-control price" disabled placeholder="0,00" /></td>' +
'</tr>';
$("#items_table tr:last").after(itemRow);
}
</script>
And I calculate it with this jQuery code:
<script>
var total = 0;
var taxTotal = 0;
(function() {
$('#items_table').on('change', 'input', function() {
if( !$(this).hasClass('tax')) {
totalPrice = 0;
var row = $(this).closest('tr');
// ## Get quantity
var qty = parseFloat(row.find('input:eq(1)').val());
if (qty < 0) {
row.addClass('danger');
return;
} else {
row.removeClass('danger');
}
// ## Get the entered price
var price = parseFloat(row.find('input:eq(3)').val());
if (price < 0) {
row.addClass('danger');
return;
} else {
row.removeClass('danger');
}
// ## Calculate total price
var total = qty * price;
// ## Set total price at the end
row.find('input:eq(4)').val(isNaN(total) ? '' : total);
tax = parseFloat(row.find('input:eq(2)').val());
var salesTax = total * (tax / 100);
if (!isNaN(salesTax)) {
$('#tax-' + row.find('input:eq(2)').val()).html(salesTax.toFixed(2));
$('#tax_percentage').html(tax + '%');
$('#tax_total').html('€ ' + salesTax.toFixed(2));
$('.price').each(function (i, obj) {
// ## Add all the prices again
totalPrice = totalPrice += parseFloat($(this).val()) + salesTax;
});
}
$('#total_price').html('€ ' + totalPrice.toFixed(2));
}else{
// ## Remove all the taxes
$('[id^=tax-tr-]').remove();
if($('#tax-'+ $(this).val()).length > 0 ){
console.log('it already exists');
}else{
$('.tax').each(function (i, obj) {
var itemRow =
'<tr id="tax-tr-' + $(this).val() + '">' +
'<td colspan="4" class="font-w600 text-right">BTW ' + $(this).val() + '%</td>' +
'<td style="width: 20%;" class="text-right">€ <span id="tax-' + $(this).val() + '">0</span></td>' +
'</tr>';
$("#subtotal_table tr").eq(-2).after(itemRow);
});
}
}
});
})();
</script>
Although, its not exactly doing what I want. I want the total price to be at the end of the table row (total price disabled row)
And I want the tax to be added below the invoice (a new table), like this:
Sub total: (Total price without tax)
TAX 10%: (The tax ammount according to the 10%)
TAX 15%: (The tax ammount according to the 15%)
Total: (Sub total price + the tax prices)
But the problem I get is once I have 2 items in the table, and I change the first row's TAX, it gets all messed up.
I am currently out of idea's how to correctly do this. So I 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 aswell, and the price has to be changed aswell.
Can someone get me back on the right track?

It's not exactly clear what you want to display in the second table,however, I believe the below will suite your needs.
Here is a jsFiddle as well
$('#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;
}
<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>
<p>Add rows and give them values for quantity and price, the script will do the rest.</p>
<p>Select a diferent tax amount to recalculate everything</p>

Related

How to clear form fields once and not every time a focus event triggers

This is driving me nuts - I know what needs to happen and I thought the scripts would work but I can't see where it's going wrong.
I've got a form that calculates a mix of products based on different inputs.
First, someone can click a radio button with a fixed amount and the form figures out the amounts based on a fixed percentage that has been determined by out product sales team. In this case, clicking on the radio buttons, resets the form and deletes any previous amount entered into the 'Other' field.
Second, if the fixed amounts aren't enough, you can enter in an amount and use the same percentage mix. This is the 'Other' field and it clears the radio buttons and the amounts in the fields.
Lastly, and the part that is causing problems, if neither fixed option is wanted, they you can enter the amounts desired in the fields and the form will keep the totals and change the percentages to suit. This also clears the radio buttons and the amount from the 'Custom' field whenever focus is placed on any one of the text fields.
However, as I move from field to field to enter amounts, the form keeps resetting itself every time I focus on the next field. I've tried to add a condition so that if no radio button is selected and the custom field is not empty, the fields are cleared. The intent is that on subsequent fields, the condition changes so that the custom field is empty and the form stops clearing the fields.
But, it's not working like that - every field that receives the focus clears the fields and I'm not having any luck figuring out how to fix it.
Sorry in advance if this is long - I'm sure the jquery could be cleaned up but this is what I have for right now.
Many thanks in advance for any and all help.
Fiddle at: https://jsfiddle.net/saabStory/cbtL0gm6/1/
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Test</title>
<style type="text/css">
* {font-family: Arial, Verdana, Helvetica, sans-serif}
.ckCustomTable {border:none;border-collapse:collapse;background-color:#fff;font-size:10pt;width:800px;}
.ckCustomTable tr th, .ckCustomTable tr td{padding:4px 2px;border:1px solid #ddd;border-collapse:collapse;background-color:#fff !important;text-align:center;}
.ckCustomTable tr th:nth-child(1),.ckCustomTable tr td:nth-child(1) {width:60px !important;}
.ckCustomTable tr th:nth-child(2),.ckCustomTable tr td:nth-child(2) {width:75px !important;}
.ckCustomTable tr th:nth-child(3),.ckCustomTable tr td:nth-child(3) {width:75px !important;}
.ckCustomTable tr th:nth-child(4),.ckCustomTable tr td:nth-child(4) {width:75px;}
.ckCustomTable tr th:nth-child(5),.ckCustomTable tr td:nth-child(5) {width:75px;}
.ckCustomTable tr th:nth-child(6),.ckCustomTable tr td:nth-child(6) {width:75px;}
.ckCustomTable tr th:nth-child(7),.ckCustomTable tr td:nth-child(7) {width:60px;}
.ckCustomTable tr th:nth-child(8),.ckCustomTable tr td:nth-child(8) {width:90px;}
.ckCustomTable tr th:nth-child(9),.ckCustomTable tr td:nth-child(9){}
.ckCustomTable tr th:nth-child(10),.ckCustomTable tr td:nth-child(10){background-color:#0f0 !important;}
.ckCustomTable tr td #tmCustom,
.ckCustomTable tr td #smCustom,
.ckCustomTable tr td #tgCustom,
.ckCustomTable tr td #trCustom,
.ckCustomTable tr td #ddCustom,
.ckCustomTable tr td #lmCustom,
.ckCustomTable tr td #ttCustom,
.ckCustomTable tr td #soCustom {text-align:center;border:1px solid #0ff;font-size:9pt;color:#666;width:35px;}
.ckCustomTable tr td #mxCustomTotal {text-align:center;padding:2px 1px;border:1px solid #ddd;font-size:9pt;color:#666;width:35px;}
.ckSelectGrid {border:none;border-collapse:collapse;width:800px;margin-bottom:10px;}
.ckSelectGrid tr td:nth-child(1),.ckSelectGrid tr td:nth-child(3),.ckSelectGrid tr td:nth-child(5),.ckSelectGrid tr td:nth-child(7),.ckSelectGrid tr td:nth-child(9) {width:50px;padding:0;text-align:right !important;border:none;border-collapse:collapse;}
.ckSelectGrid tr td:nth-child(2),.ckSelectGrid tr td:nth-child(4),.ckSelectGrid tr td:nth-child(6),.ckSelectGrid tr td:nth-child(8),.ckSelectGrid tr td:nth-child(10) {width:100px;text-align:left;border:none;border-collapse:collapse;padding-left:0;}
.ckSelectGrid tr td:nth-child(9) {width:80px !important;}
.ckSelectGrid tr td:nth-child(10) {width:90px !important;padding:0;margin:0;}
</style>
</head>
<body>
<table class="ckSelectGrid" id="selectAmt">
<tr>
<td><input type="radio" name="cookieSelect" id="count100" class="" value="100"></td>
<td class="paddingLeft10"><label class="font105" for="count100">100</label></td>
<td><input type="radio" name="cookieSelect" id="count250" class="" value="250"></td>
<td><label class="font105" for="count250">250</label></td>
<td><input type="radio" name="cookieSelect" id="count300" class="" value="300"></td>
<td><label class="font105" for="count300">300</label></td>
<td><input type="radio" name="cookieSelect" id="count600" class="" value="600"></td>
<td><label class="font105" for="count600">600</label></td>
<td><label class="font105 paddingRight10" for="cookieGoal">Other</label></td>
<td><input type="text" id="countOther" name="countOther" class="form_Field60 key-numeric" style="font-size:9pt !important;" tabindex="1" autocomplete="nope" /></td>
</tr>
</table>
<table class="ckCustomTable">
<tr>
<th>ITEM</th>
<th>TM</th>
<th>SM</th>
<th>TG</th>
<th>TR</th>
<th>DD</th>
<th>LM</th>
<th>TT</th>
<th>SO</th>
<th>Total</th>
</tr>
<tr>
<td>Mix %</td>
<td id="tmPercent">27%</td>
<td id="smPercent">23%</td>
<td id="tgPercent">15%</td>
<td id="trPercent">9%</td>
<td id="ddPercent">8%</td>
<td id="lmPercent">9%</td>
<td id="ttPercent">2%</td>
<td id="soPercent">7%</td>
<td id="mxPercent">100%</td>
</tr>
<tr>
<td >AMT:</td>
<td><input type="text" style="width:50px;padding:5px 0;border:1px solid #ccc;" class="key-numeric textCenter" name="tmTotal" id="tmTotal" tabindex="10" value=""></td>
<td><input type="text" style="width:50px;padding:5px 0;border:1px solid #ccc;" class="key-numeric textCenter" name="smTotal" id="smTotal" tabindex="11" value=""></td>
<td><input type="text" style="width:50px;padding:5px 0;border:1px solid #ccc;" class="key-numeric textCenter" name="tgTotal" id="tgTotal" tabindex="12" value=""></td>
<td><input type="text" style="width:50px;padding:5px 0;border:1px solid #ccc;" class="key-numeric textCenter" name="trTotal" id="trTotal" tabindex="13" value=""></td>
<td><input type="text" style="width:50px;padding:5px 0;border:1px solid #ccc;" class="key-numeric textCenter" name="ddTotal" id="ddTotal" tabindex="14" value=""></td>
<td><input type="text" style="width:50px;padding:5px 0;border:1px solid #ccc;" class="key-numeric textCenter" name="lmTotal" id="lmTotal" tabindex="15" value=""></td>
<td><input type="text" style="width:50px;padding:5px 0;border:1px solid #ccc;" class="key-numeric textCenter" name="ttTotal" id="ttTotal" tabindex="16" value=""></td>
<td><input type="text" style="width:50px;padding:5px 0;border:1px solid #ccc;" class="key-numeric textCenter" name="soTotal" id="soTotal" tabindex="17" value=""></td>
<td><input type="text" style="width:50px;padding:5px 0;border:1px solid #ccc;" class="key-numeric textCenter" name="mxTotal" id="mxTotal" readonly tabindex="-1" value=""></td>
</tr>
</table>
<input type="text" name="countOtherTemp" id="countOtherTemp" placeholder="Count Other Temp" tabindex="-1" value="">
<input type="text" name="tmTotalTemp" id="tmTotalTemp" placeholder="TMTemp" tabindex="-1" value="">
<input type="text" name="smTotalTemp" id="smTotalTemp" placeholder="SMTemp" tabindex="-1" value="">
<input type="text" name="tgTotalTemp" id="tgTotalTemp" placeholder="TGTemp" tabindex="-1" value="">
<input type="text" name="trTotalTemp" id="trTotalTemp" placeholder="TRTemp" tabindex="-1" value="">
<input type="text" name="ddTotalTemp" id="ddTotalTemp" placeholder="DDTemp" tabindex="-1" value="">
<input type="text" name="lmTotalTemp" id="lmTotalTemp" placeholder="LMTemp" tabindex="-1" value="">
<input type="text" name="ttTotalTemp" id="ttTotalTemp" placeholder="TTTemp" tabindex="-1" value="">
<input type="text" name="soTotalTemp" id="soTotalTemp" placeholder="SOTemp" tabindex="-1" value="">
<input type="text" name="mxTotalTemp" id="mxTotalTemp" placeholder="MXTemp" tabindex="-1" value="">
<script src="https://code.jquery.com/jquery-3.4.1.min.js" ></script> <!-- V 1.11.2 -->
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script> <!-- V 1.11.2 -->
<script type="application/javascript">
$('.key-numeric').keypress(function(e) {
var verified = (e.which == 8 || e.which == undefined || e.which == 0) ? null : String.fromCharCode(e.which).match(/[^0-9]/);
if (verified) {e.preventDefault();}
});
$(document).ready(function () {
//= CUSTOM MIX CALCULATIONS ====================================================================================================================================
// INITIALIZE STANDARD COOKIE MIX VARS =====================================================================================================================
var tmTotalTemp = null;
var smTotalTemp = null;
var tgTotalTemp = null;
var trTotalTemp = null;
var ddTotalTemp = null;
var lmTotalTemp = null;
var ttTotalTemp = null;
var soTotalTemp = null;
var mxTotalTemp = null;
var countOtherTemp = null;
//= RADIO BUTTON SELECTION =================================================================================================================================
$("#selectAmt :radio").change(function() {
$("#countOther,#countOtherTemp").val('');
$("#tmPercent").html("27%");
$("#smPercent").html("23%");
$("#tgPercent").html("15%");
$("#trPercent").html("9%");
$("#ddPercent").html("8%");
$("#lmPercent").html("9%");
$("#ttPercent").html("2%");
$("#soPercent").html("7%");
$("#mxPercent").html("100%");
tmTotalTemp = parseInt(Math.round(this.value)*.27);
smTotalTemp = parseInt(Math.round(this.value)*.23);
tgTotalTemp = parseInt(Math.round(this.value)*.15);
trTotalTemp = parseInt(Math.round(this.value)*.09);
ddTotalTemp = parseInt(Math.round(this.value)*.08);
lmTotalTemp = parseInt(Math.round(this.value)*.09);
ttTotalTemp = parseInt(Math.round(this.value)*.02);
soTotalTemp = parseInt(Math.round(this.value)*.07);
mxTotalTemp = Math.round(tmTotalTemp + smTotalTemp + tgTotalTemp + trTotalTemp + ddTotalTemp + lmTotalTemp + ttTotalTemp + soTotalTemp);
$("#tmTotal").val(tmTotalTemp);
$("#smTotal").val(smTotalTemp);
$("#tgTotal").val(tgTotalTemp);
$("#trTotal").val(trTotalTemp);
$("#ddTotal").val(ddTotalTemp);
$("#lmTotal").val(lmTotalTemp);
$("#ttTotal").val(ttTotalTemp);
$("#soTotal").val(soTotalTemp);
$("#mxTotal").val(mxTotalTemp);
$("#countOther").val(countOtherTemp);
$("#tmTotalTemp").val(tmTotalTemp);
$("#smTotalTemp").val(smTotalTemp);
$("#tgTotalTemp").val(tgTotalTemp);
$("#trTotalTemp").val(trTotalTemp);
$("#ddTotalTemp").val(ddTotalTemp);
$("#lmTotalTemp").val(lmTotalTemp);
$("#ttTotalTemp").val(ttTotalTemp);
$("#soTotalTemp").val(soTotalTemp);
$("#mxTotalTemp").val(mxTotalTemp);
});
//= OTHER AMOUNT CALCULATION ===============================================================================================================================
$('#countOther').on("input",function(){
$("#countOtherTemp").val($('#countOther').val());
$("#tmPercent").html("27%");
$("#smPercent").html("23%");
$("#tgPercent").html("15%");
$("#trPercent").html("9%");
$("#ddPercent").html("8%");
$("#lmPercent").html("9%");
$("#ttPercent").html("2%");
$("#soPercent").html("7%");
$("#mxPercent").html("100%");
$("#count100,#count250,#count300,#count600").attr('checked', false);
$("#tmTotal,#smTotal,#tgTotal,#trTotal,#ddTotal,#lmTotal,#ttTotal,#soTotal,#mxTotal").val('');
$("#tmTotalTemp,#smTotalTemp,#tgTotalTemp,#trTotalTemp,#ddTotalTemp,#lmTotalTemp,#ttTotalTemp,#soTotalTemp,#mxTotalTemp").val('');
$("#tmTotal,#tmTotalTemp").val(Math.round($('#countOther').val()*.27));
$("#smTotal,#smTotalTemp").val(Math.round($('#countOther').val()*.23));
$("#tgTotal,#tgTotalTemp").val(Math.round($('#countOther').val()*.15));
$("#trTotal,#trTotalTemp").val(Math.round($('#countOther').val()*.09));
$("#ddTotal,#ddTotalTemp").val(Math.round($('#countOther').val()*.08));
$("#lmTotal,#lmTotalTemp").val(Math.round($('#countOther').val()*.09));
$("#ttTotal,#ttTotalTemp").val(Math.round($('#countOther').val()*.02));
$("#soTotal,#soTotalTemp").val(Math.round($('#countOther').val()*.07));
$("#mxTotal,#mxTotalTemp").val(Number($("#tmTotal").val()) + Number($("#smTotal").val()) + Number($("#tgTotal").val()) + Number($("#trTotal").val()) + Number($("#ddTotal").val()) + Number($("#lmTotal").val()) + Number($("#ttTotal").val()) + Number($("#soTotal").val()) + Number($("#mxTotal").val()));
});
//= CUSTOM COOKIE MIX CALCULATIONS =============================================================================================================================
// INITIALIZE CUSTOM COOKIE MIX VARS =======================================================================================================================
$('#tmTotal,#smTotal,#tgTotal,#trTotal,#ddTotal,#lmTotal,#ttTotal,#soTotal').focus(function() {
$("#amountOther").val('');
var radioCheck = $('input:radio[name=cookieSelect]:checked').val();
if (radioCheck || ($("#amountOther").val() !== '')) {
$("#count100,#count250,#count300,#count600").prop("checked", false);
$("#tmTotal,#smTotal,#tgTotal,#trTotal,#ddTotal,#lmTotal,#ttTotal,#soTotal,#mxTotal,#countOther").val('');
// return false;
}
});
$("#tmTotal").each(function(){ //= CALCULATE SUM FOR PRODUCTS ===================================================
$(this).on("input",function(){
calculateOrderSum();
});
});
$("#smTotal").each(function(){ //= CALCULATE SUM FOR PRODUCTS ===================================================
$(this).on("input",function(){
calculateOrderSum();
});
});
$("#tgTotal").each(function(){ //= CALCULATE SUM FOR PRODUCTS ===================================================
$(this).on("input",function(){
calculateOrderSum();
});
});
$("#trTotal").each(function(){ //= CALCULATE SUM FOR PRODUCTS ===================================================
$(this).on("input",function(){
calculateOrderSum();
});
});
$("#ddTotal").each(function(){ //= CALCULATE SUM FOR PRODUCTS ===================================================
$(this).on("input",function(){
calculateOrderSum();
});
});
$("#lmTotal").each(function(){ //= CALCULATE SUM FOR PRODUCTS ===================================================
$(this).on("input",function(){
calculateOrderSum();
});
});
$("#ttTotal").each(function(){ //= CALCULATE SUM FOR PRODUCTS ===================================================
$(this).on("input",function(){
calculateOrderSum();
});
});
$("#soTotal").each(function(){ //= CALCULATE SUM FOR PRODUCTS ===================================================
$(this).on("input",function(){
calculateOrderSum();
});
});
function calculateOrderSum() {
var tm = Number($('#tmTotal').val());
var sm = Number($('#smTotal').val());
var tg = Number($('#tgTotal').val());
var tr = Number($('#trTotal').val());
var dd = Number($('#ddTotal').val());
var lm = Number($('#lmTotal').val());
var tt = Number($('#ttTotal').val());
var so = Number($('#soTotal').val());
var mx = tm + sm + tg + tr + dd + lm + tt + so
$("#mxTotal").val(mx);
//= POPULATE TEMP FIELDS ===========================================================================================================================================
$("#tmTotalTemp").val(tm);
$("#smTotalTemp").val(sm);
$("#tgTotalTemp").val(tg);
$("#trTotalTemp").val(tr);
$("#ddTotalTemp").val(dd);
$("#lmTotalTemp").val(lm);
$("#ttTotalTemp").val(tt);
$("#soTotalTemp").val(so);
$("#mxTotalTemp").val(mx);
//= CALCULATE PERCENTAGES ==========================================================================================================================================
var tmPercent = Math.round((($("#tmTotal").val()) / ($("#mxTotal").val())) * 100);
var smPercent = Math.round((($("#smTotal").val()) / ($("#mxTotal").val())) * 100);
var tgPercent = Math.round((($("#tgTotal").val()) / ($("#mxTotal").val())) * 100);
var trPercent = Math.round((($("#trTotal").val()) / ($("#mxTotal").val())) * 100);
var ddPercent = Math.round((($("#ddTotal").val()) / ($("#mxTotal").val())) * 100);
var lmPercent = Math.round((($("#lmTotal").val()) / ($("#mxTotal").val())) * 100);
var ttPercent = Math.round((($("#ttTotal").val()) / ($("#mxTotal").val())) * 100);
var soPercent = Math.round((($("#soTotal").val()) / ($("#mxTotal").val())) * 100);
var mxPercent = (tmPercent + smPercent + tgPercent + trPercent + ddPercent + lmPercent + ttPercent + soPercent);
$("#tmPercent").html(tmPercent + "%");
$("#smPercent").html(smPercent + "%");
$("#tgPercent").html(tgPercent + "%");
$("#trPercent").html(trPercent + "%");
$("#ddPercent").html(ddPercent + "%");
$("#lmPercent").html(lmPercent + "%");
$("#ttPercent").html(ttPercent + "%");
$("#soPercent").html(soPercent + "%");
$("#mxPercent").html(mxPercent + "%");
}
});
</script>
</body>
It's a simple mistake, but it looks like this might be it:
Simply change every instance of #amountOther to #countOther.
Specifically in here:
$('#tmTotal,#smTotal,#tgTotal,#trTotal,#ddTotal,#lmTotal,#ttTotal,#soTotal').focus(function() {
$("#amountOther").val('');
var radioCheck = $('input:radio[name=cookieSelect]:checked').val();
if (radioCheck || ($("#amountOther").val() !== '')) {
$("#count100,#count250,#count300,#count600").prop("checked", false);
$("#tmTotal,#smTotal,#tgTotal,#trTotal,#ddTotal,#lmTotal,#ttTotal,#soTotal,#mxTotal,#countOther").val('');
// return false;
}
});
Change to this:
$('#tmTotal,#smTotal,#tgTotal,#trTotal,#ddTotal,#lmTotal,#ttTotal,#soTotal').focus(function() {
//**This line below**
$("#countOther").val('');
var radioCheck = $('input:radio[name=cookieSelect]:checked').val();
//**Also the line below here**
if (radioCheck || ($("#countOther").val() !== '')) {
$("#count100,#count250,#count300,#count600").prop("checked", false);
$("#tmTotal,#smTotal,#tgTotal,#trTotal,#ddTotal,#lmTotal,#ttTotal,#soTotal,#mxTotal,#countOther").val('');
// return false;
}
});

Get all values per table column dynamically using javascript or jquery

I need to get all values per column dynamically and save it using JS or Jquery. I have a photo here so that you guys can visualize what I am trying to do. Please see the image.
Sad to say this is as far as I can go. I cant seems to get what I realy want to achieve. Just a beginner here.
$(function() {
$('#add_supplier').click(function() {
$('#supplier_table > thead > tr#first-header').append(
'<th colspan="2" class="supplier_name"><input type="text" class="form-control" placeholder="Enter Supplier" style="text-align: center;"></th>'
);
$('#supplier_table > thead > tr#second-header').append(
'<th>Price</th>' +
'<th>Total</th>'
);
$('#supplier_table > tbody > tr').not('#totals,#tr-td-2').append(
'<td class="ignore"><input type="text" class="form-control price text-right" ></td>' +
'<td><input type="text" class="form-control total text-right" readonly></td>'
);
$('#supplier_table > tbody > #totals').not('#tr-td-2').append(
'<td class="ignore"><input class="form-control" disabled></td>' +
'<td><input type="text" class="form-control grandtotal text-right" readonly=""></td>'
);
$('#supplier_table > tbody > #tr-td-2').append(
'<td colspan="2" style="width: 160px;"><input style="text-align: center;" class="form-control" type="text"></td>'
);
//
refresh_index();
//
});
$('#add_terms').click(function() {
var $tableBody = $('#supplier_table').find("tbody").not('#totals'),
$trLast = $tableBody.find("tr:last"),
$trNew = $trLast.clone();
$trNew.find('input').val('');
$trLast.after($trNew);
refresh_index();
});
// $('#add_supplier').click();
$('#add_item').click(function() {
$('#supplier_table > tbody').not('#totals, #tr-td-2').append(
// $("#supplier_table tbody tr:last").clone()
'<tr class="tbody-tr">' +
'<td class="ignore"><input type="text" class="form-control " value="Monitor" readonly=""></td>' +
'<td class="ignore"><input type="text" class="form-control qty" value="30" readonly=""></td>' +
'<td class="ignore"><input type="text" class="form-control price"></td>' +
'<td><input type="text" class="form-control total for_sum-1" readonly=""></td>' +
'</tr>'
);
//
refresh_index();
//
});
//
function refresh_index() {
$('.price').each(function(i) {
i++;
$(this).attr('id', 'price-' + i);
$(this).attr('data-num', i);
event_handler();
});
$('.total').each(function(i) {
i++;
$(this).attr('id', 'total-' + i);
});
$('.qty').each(function(i) {
i++;
$(this).attr('id', 'qty-' + i);
});
$('.grandtotal').each(function(i) {
i++;
$(this).attr('id', 'grandtotal-' + i);
});
$('.supplier_name').each(function(i) {
i++;
$(this).attr('id', 'supplier_name-' + i);
});
}
refresh_index();
//
//
function event_handler() {
$('.price').unbind('keyup').bind('keyup', function() {
var id = this.id;
var num = id.split('-');
var pos = $(this).closest('tr').index() + 1;
var qty = $('#qty-' + pos).val();
var price = $(this).val();
var total = parseFloat(qty) * parseFloat(price);
if (isNaN(total)) {
var total = 0;
}
$('#total-' + num[1]).text(total);
$('#total-' + num[1]).val(total);
var num_of_supplier_name = $('.supplier_name').length;
sum_of_total();
});
}
function sum_of_total() {
// var sum = 0;
// //iterate through each textboxes and add the values
// $(".total").each(function () {
// //add only if the value is number
// if (!isNaN($(this).val()) && $(this).val().length != 0) {
// sum += parseFloat(this.value);
// }
// });
// //.toFixed() method will roundoff the final sum to 2 decimal places
// $("#grandtotal-"+num).val(sum);
var totals = [];
$('#tb').find('tr').each(function() {
var $row = $(this);
$row.children('td').not('.ignore').each(function(index) {
totals[index] = totals[index] || 0;
totals[index] += parseInt($(this).text()) || 0;
});
})
$('#totals td').not('.ignore').each(function(index) {
// $(this).text(totals[index]);
var id = index + 1;
$('#grandtotal-' + id).val(totals[index]);
});
$("#tb").on("click", "tr", function() {
$(this).find("td").slice(0, 4).prop("contenteditable", true);
});
// var max = 0;
// $('.grandtotal').each(function()
// {
// $this = parseInt( $(this).val() );
// // console.log($this);
// if ($this > max) {
// max = $this;
// }
// // $('.grandtotal').val(max).css('background-color','yellow');
// // console.log('Lowest Offer : '+max);
// });
// console.log('Lowest Offer : '+max);
// var high = Math.min.apply(Math, $('.grandtotal').map(function(){
// return $(this).val()
// }))
// console.log('Lowest Offer : '+high);
var vals = $('.grandtotal').map(function() {
return parseInt($(this).val(), 10) ? parseInt($(this).val(), 10) : null;
}).get();
// then find their minimum
var min = Math.min.apply(Math, vals);
console.log(min);
// tag any cell matching the min value
$('.grandtotal').filter(function() {
// return parseInt($(this).val(), 10) === min;
if (parseInt($(this).val(), 10) === min) {
$(this).css("background-color", "#dff0d8");
} else {
$(this).css("background-color", "transparent");
}
});
}
//
});
<button type="button" class="btn btn-success" id="add_supplier">Add Supplier</button>
<!-- <button type="button" class="btn btn-default" id="add_item">Add Item</button> -->
<button type="button" class="btn btn-primary" id="add_terms">Add Terms</button>
<table class="table table-bordered" id="supplier_table">
<thead>
<tr id="first-header">
<th></th>
<th></th>
<th colspan="2" class="supplier_name" id="supplier_name-1"><input type="text" class="form-control" placeholder="Enter Supplier" style="text-align: center;"></th>
</tr>
<tr id="second-header">
<th>Item</th>
<th>Qty</th>
<th>Price</th>
<th>Total</th>
</tr>
</thead>
<tbody id="tb">
<tr class="tbody-tr">
<td class="ignore"><input type="text" class="form-control" value="Mouse" readonly=""></td>
<td class="ignore"><input type="text" class="form-control qty" value="10" readonly=""></td>
<td class="ignore"><input type="text" class="form-control price"></td>
<td><input type="text" class="form-control total for_sum-1" readonly=""></td>
</tr>
<tr class="tbody-tr">
<td class="ignore"><input type="text" class="form-control" value="Keyboard" readonly=""></td>
<td class="ignore"><input type="text" class="form-control qty" value="20" readonly=""></td>
<td class="ignore"><input type="text" class="form-control price"></td>
<td><input type="text" class="form-control total for_sum-1" readonly=""></td>
</tr>
<tr class="tbody-tr">
<td class="ignore"><input type="text" class="form-control " value="Monitor" readonly=""></td>
<td class="ignore"><input type="text" class="form-control qty" value="30" readonly=""></td>
<td class="ignore"><input type="text" class="form-control price"></td>
<td><input type="text" class="form-control total for_sum-1" readonly=""></td>
</tr>
<tr id="totals">
<td class="ignore"></td>
<td class="ignore"></td>
<td class="ignore"><input class="form-control" disabled value="Grand Total : " style="text-align: right;"></td>
<td><input type="text" class="form-control grandtotal text-right" readonly=""></td>
</tr>
<tr id="tr-td-2">
<td>
<p style="width: 60px;"></p>
</td>
<td><input style="font-weight: bold; text-align: right;" type="text" class="form-control" placeholder="Enter terms"></td>
<!-- <td ><p style="width: 60px;"></p></td> -->
<td colspan="2" style="width: 160px;"><input style="text-align: center;" class="form-control" type="text"></td>
</tr>
</tbody>
</table>
Actual Demo Link
JSFIDDLE

Comparing two values with dynamic rows using javascript

I have an html code with multiple rows containing two values.Using javascript,I am able to compare the two values for only one row.How can I do the same for dynamically generated rows.
HTML:
<tbody id="appendrow" class="appendrow">
<input type="text"
data-field="quantity"
required
class="form-control"
name="units_ordered[]"
id="units_ordered0"
value=""/>
<input type="text"
data-field="inventory"
class="form-control"
name="inventory"
id="inventory0"
value="" />
</tbody>
Javascript:
var counter = 1;
$(window).load(function () {
$(function () {
$('#addRow').click(function () {
var row = $(' <tbody id=\'appendrow\' class=\'appendrow\'><tr><td> <input type=\'text\' required class=\'form-control\' name=\'sku[]\' onclick=\'filtersku(this,' + counter + ');\'> <input type=\'hidden\' id=\'product_id' + counter + '\' name=\'product_id[]\'/></td> <td> <input type=\'text\' readonly data-field=\'vendorsku\' id=\'vendor_sku' + counter + '\' name=\'vendorsku[]\'class=\'form-control\'></td> <td><input class=\'form-control\' data-field=\'quantity\' type=\'text\' required id=units_ordered' + counter + '\' name=\'units_ordered[]\' /></td> <td><input class=\'form-control\' type=\'text\' data-field=\'price\' required name=\'vendor_unit_price[]\' id=\'vendor_price' + counter + '\'></td> <td><input name=\'discount_percent[]\' data-field=\'discount\' class=\'form-control\' ><input type=\'hidden\' data-field=\'discountnumber\' class=\'form-control\' id=\'discountnumber\' ></td><td><input type=\'text\' readonly data-field=\'tax\' id=\'tax_id' + counter + '\' class=\'form-control\' name=\'tax_id[]\' /></td><td> Rs. <span data-field=\'taxPrice\' id=\'taxPrice' + counter + '\' >0</span><input type=\'hidden\' data-field=\'taxPriceInput\' id=\'taxPriceInput' + counter + '\' class=\'taxPrice\' value = \'0\'/> </td> <td><input type=\'text\' class=\'form-control\'data-field=\'total\' name=\'subtotal[]\'/><input type=\'hidden\' data-field=\'totalbeforetax\' class=\'form-control\' id=\'subtotalbeforetax\' /></td><td><button type=\'button\' class=\'btn btn-danger\' name=\'delete[]\' onclick=\'javascript:deletefun(this);\'><i class=\'fa fa-trash\' aria-hidden=\'true\'></i></button></td></tr></tbody>');
$('#example').append(row);
counter++;
});
});
});
function validation() {
var ordered = parseInt(document.getElementById('units_ordered0').value);
var inventory = parseInt(document.getElementById('inventory0').value);
if (inventory == -1) {
return true;
}
else {
if (ordered <= inventory) {
return true;
}
else {
document.getElementById('error').innerHTML = ('Ordered units of a product cannot be greater than the number of products present in inventory whose value is ' + inventory).fontcolor('red');
return false;
}
}
}
Please note the correct structure of the HTML5 Table. Here is a clean HTML5 Table structure:
<table>
<caption>Table Caption</caption>
<colgroup>
<col>
<col>
</colgroup>
<thead>
<tr>
<th>Header Row 1</th>
<th>Header Row 2</th>
<th>Header Row 3</th>
</tr>
</thead>
<tfoot>
<tr>
<td>Footer Row 1</td>
<td>Footer Row 2</td>
<td>Footer Row 3</td>
</tr>
</tfoot>
<tbody>
<tr>
<td>Body Row 1</td>
<td>Body Row 2</td>
<td>Body Row 3</td>
</tr>
</tbody>
</table>
And about your question:
var counter = 1;
document.getElementById( 'addRow' ).addEventListener( 'click', function ( e ) {
var table = document.getElementById( 'myTable' ),
row = table.insertRow( counter ),
cell1 = row.insertCell( 0 ),
cell2 = row.insertCell( 1 );
cell1.innerHTML = '<input type="text" data-field="quantity" class="form-control" name="units_ordered[]" id="units_ordered' + counter + '" required/>';
cell2.innerHTML = '<input type="text" data-field="inventory" class="form-control" name="inventory" id="inventory' + counter + '"/>';
counter++;
e.preventDefault()
} )
document.getElementById( 'validate' ).addEventListener( 'click', function ( e ) {
validation();
e.preventDefault()
} )
function validation() {
var ordered = document.querySelectorAll( 'input[id^="units_ordered"]' ),
inventory = document.querySelectorAll( 'input[id^="inventory"]' );
document.getElementById( 'error' ).innerHTML = ''
ordered.forEach( function ( item, index ) {
var ordered_val = Number( item.value ) || 0,
inventory_val = Number( inventory[ index ].value ) || 0
if ( inventory_val == -1 ) {
return true
} else {
if ( ordered_val <= inventory_val ) {
return true
} else {
document.getElementById( 'error' ).innerHTML += 'Row ' + +( index + 1 ) + ': Ordered units of a product cannot be greater than the number of products present in inventory whose value is ' + inventory_val + '<br/>';
return false
}
}
} )
}
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 300px
}
td, th {
border: 1px solid #86af49;
text-align: left;
padding: 0
}
th {
padding: 5px;
color: #fff;
background-color: #86af49
}
input[type="text"] {
box-sizing: border-box;
width: 100%;
border: 0;
outline: none
}
#error {
color: red;
font-size: .75em
}
<p>
<button type="button" id="addRow">Add Row</button>
<button type="button" id="validate">Validation</button>
</p>
<table id="myTable">
<thead>
<tr>
<th>Ordered</th>
<th>Inventory</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<input type="text" data-field="quantity" class="form-control" name="units_ordered[]" id="units_ordered0" required/>
</td>
<td>
<input type="text" data-field="inventory" class="form-control" name="inventory" id="inventory0"/>
</td>
</tr>
</tbody>
</table>
<p id="error"></p>

Minor change required with this Javascript Code

So this is the code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style type="text/css">
body{font-family:Arial, Helvetica, sans-serif;font-size:12px;}
table{width:700px;margin:auto;border:solid 5px #cccccc}
table th{border-right:solid 1px #cccccc;border-bottom:solid 1px #000000;padding:5px;}
table th:last-child{border-right:0px;}
table td{border-right:solid 1px #d0d7e5;border-bottom:solid 1px #d0d7e5;}
table td:last-child{border-right:0px;}
table tr:last-child td{border-bottom:0px;}
table td input{padding:5px 0px;margin:auto;white-space:nowrap;overflow:hidden;outline:none;border:solid 1px #ffffff;text-align:center;width:99%;}
table td input.green{background:#00b050;border:solid 1px #00b050;}
table td input.red{background:#ff0000;border:solid 1px #ff0000;}
table td.active input{border:dotted 1px #333333;}
</style>
<script type="text/javascript" src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
var row_template = "<tr><td><input type='text' value='0.00' maxlength='5' /></td><td><input type='text' value='0.00' maxlength='5' /></td><td><input type='text' value='0.00' maxlength='5' /></td></tr>";
var active_row;
var active_col;
// Initialize cell width
//$("table td").each(function()
//{
//var width = $(this).width();
//$(this).find("input").width(width-2);
//});
//----------------------
// Set Focus of cell
$("table").on("focus", "tr td input", function()
{
var row_count = $("table tr").size()-1;
$("table td").removeClass();
active_col = $(this).closest("td").index()+1;
active_row = $(this).closest("tr").index();
$(this).parent().addClass("active");
$(this).val("");
if(active_row == row_count)
{
$("table").append(row_template);
}
});
//------------------
// Set Blue of cell
$("table").on("blur", "tr td input", function(e)
{
var value = $(this).val();
if(isNaN(value) || value == "")
{
value = 0;
}
$(this).val(parseFloat(value).toFixed(2));
format_cell(active_row, active_col);
});
//-----------------
// Enter key on cell
$("table").on("keydown", "tr td input", function(e)
{
var value = $(this).val();
if(e.keyCode == 13)
{
$(this).blur();
if(active_col == 2)
{
$("table tr").eq(active_row).find("td").eq(active_col).find("input").focus();
}
else if(active_col == 3)
{
$("table tr").eq(active_row+1).find("td").eq(active_col-2).find("input").focus();
}
return(false);
}
else
{
if(value.length == 2)
{
$(this).val(value+".");
}
}
});
//------------------
// Download data
$("#btn_download").click(function()
{
var json = "";
var movement;
var pdi;
var ndi;
json += "[";
json += '{"movement":"Movement","pdi":"PDI","ndi":"NDI"},';
$("table tr:gt(0)").each(function(r)
{
movement = $(this).find("td").eq(0).find("input").val();
pdi = $(this).find("td").eq(1).find("input").val();
ndi = $(this).find("td").eq(2).find("input").val();
movement = (movement==0?"0":movement);
pdi = (pdi==0?"0":pdi);
ndi = (ndi==0?"0":ndi);
if(r==0)
{
json += '{"movement":"'+movement+'","pdi":"'+pdi+'","ndi":"'+ndi+'"}';
}
else
{
json += ',{"movement":"'+movement+'","pdi":"'+pdi+'","ndi":"'+ndi+'"}';
}
});
json += "]";
var csv = json_to_csv(json);
window.open("data:text/csv;charset=utf-8," + escape(csv));
});
//--------------
});
function format_cell(row, col, pre_value)
{
var pre_value = $("table tr").eq(row-1).find("td").eq(col-1).find("input").val();
var value = $("table tr").eq(row).find("td").eq(col-1).find("input").val();
if(col == 3)
{
if(parseFloat(value) < parseFloat(pre_value))
{
$("table tr").eq(row).find("td").eq(col-1).addClass("active").find("input").removeClass("red").addClass("green");
}
else if(parseFloat(value) > parseFloat(pre_value))
{
$("table tr").eq(row).find("td").eq(col-1).addClass("active").find("input").removeClass("green").addClass("red");
}
else
{
$("table tr").eq(row).find("td").eq(col-1).addClass("active").find("input").removeClass("green red");
}
}
else
{
if(parseFloat(value) > parseFloat(pre_value))
{
$("table tr").eq(row).find("td").eq(col-1).addClass("active").find("input").removeClass("red").addClass("green");
}
else if(parseFloat(value) < parseFloat(pre_value))
{
$("table tr").eq(row).find("td").eq(col-1).addClass("active").find("input").removeClass("green").addClass("red");
}
else
{
$("table tr").eq(row).find("td").eq(col-1).addClass("active").find("input").removeClass("green red");
}
}
calculate_grid();
}
function calculate_grid()
{
$("table tr:gt(0)").each(function(r)
{
var pdi = $(this).find("td").eq(1).find("input").val();
var ndi = $(this).find("td").eq(2).find("input").val();
var movement = (parseFloat(pdi) - parseFloat(ndi)).toFixed(2);
r=r+1;
$(this).find("td").eq(0).find("input").val(movement);
if(movement > 0)
{
$(this).find("td").eq(0).find("input").removeClass("red").addClass("green");
}
else if(movement < 0)
{
$(this).find("td").eq(0).find("input").removeClass("green").addClass("red");
}
else
{
$(this).find("td").eq(0).find("input").removeClass("green red");
}
});
}
function json_to_csv(objArray)
{
var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
var str = "";
var line = "";
if($("#labels").is(':checked'))
{
var head = array[0];
if($("#quote").is(':checked'))
{
for(var index in array[0])
{
var value = index + "";
line += '"' + value.replace(/"/g, '""') + '",';
}
}
else
{
for(var index in array[0])
{
line += index + ',';
}
}
line = line.slice(0, -1);
str += line + '\r\n';
}
for(var i=0;i<array.length;i++)
{
var line = "";
if ($("#quote").is(':checked'))
{
for (var index in array[i])
{
var value = array[i][index] + "";
line += '"' + value.replace(/"/g, '""') + '",';
}
}
else
{
for(var index in array[i])
{
line += array[i][index] + ',';
}
}
line = line.slice(0, -1);
str += line + '\r\n';
}
return(str);
}
</script>
<title>Excel</title>
</head>
<body>
<table border="0" cellspacing="0" cellpadding="0">
<tr>
<th width="30%">Movement Data</th>
<th width="35%">PDI</th>
<th width="35%">NDI</th>
</tr>
<tr>
<td><input type="text" value="0.00" maxlength="5" /></td>
<td><input type="text" value="0.00" maxlength="5" /></td>
<td><input type="text" value="0.00" maxlength="5" /></td>
</tr>
<tr>
<td><input type="text" value="0.00" maxlength="5" /></td>
<td><input type="text" value="0.00" maxlength="5" /></td>
<td><input type="text" value="0.00" maxlength="5" /></td>
</tr>
<tr>
<td><input type="text" value="0.00" maxlength="5" /></td>
<td><input type="text" value="0.00" maxlength="5" /></td>
<td><input type="text" value="0.00" maxlength="5" /></td>
</tr>
<tr>
<td><input type="text" value="0.00" maxlength="5" /></td>
<td><input type="text" value="0.00" maxlength="5" /></td>
<td><input type="text" value="0.00" maxlength="5" /></td>
</tr>
<tr>
<td><input type="text" value="0.00" maxlength="5" /></td>
<td><input type="text" value="0.00" maxlength="5" /></td>
<td><input type="text" value="0.00" maxlength="5" /></td>
</tr>
</table>
<center><input type="button" id="btn_download" value="Download" /></center>
</body>
</html>
I want to change color in the movement cell according to the data. If the the current value is lower than the preceding value I want it to be red and if the current value is more than the preceding value than I want it to be green. I believe it requires a minor change in the "movement function"
Please help.
Here is a jsfiddle for the scenario: Click Here
Is this not what already happens. I have tested the jsfiddle (http://jsfiddle.net/4QBwK/), behaviour seems a little odd, but I think it fits what you have specified.
The only change I think is needed is to remove most of the code from the format_cell() function that seems to randomly light up cells in either red or green. I have commented it out on this jsfiddle: http://jsfiddle.net/4QBwK/1/
So you would just have this instead:
function format_cell(row, col, pre_value)
{
calculate_grid();
}

jquery to sum two inputs on dynamic table and display in third

With the SO community I have got a script that adds rows with unique names to a table. I want to take two inputs on each row and multiply them together and display result in a third input.
the fiddle is at http://jsfiddle.net/yUfhL/231/
My code is:
HTML
<table class="order-list">
<tr><td>Product</td><td>Price</td><td>Qty</td><td>Total</td></tr>
<tr>
<td><input type="text" name="product" /></td>
<td><input type="text" name="price" /></td>
<td><input type="text" name="qty" /></td>
<td><input type="text" name="linetotal" /></td>
</tr>
</table>
<div id="grandtotal">
Grand Total Here
</div>
JS
var counter = 1;
jQuery("table.order-list").on('change','input[name^="product"]',function(event){
event.preventDefault();
counter++;
var newRow = jQuery('<tr><td><input type="text" name="product' +
counter + '"/></td><td><input type="text" name="price' +
counter + '"/></td><td><input type="text" name="qty' +
counter + '"/></td><td><input type="text" name="total' +
counter + '"/></td><td><a class="deleteRow"> x </a></td></tr>');
jQuery('table.order-list').append(newRow);
});
jQuery("table.order-list").on('click','.deleteRow',function(event){
$(this).closest('tr').remove();
});
$('table.order-list tr').each(function() {
var price = parseInt( $('input[id^=price]', this).val(), 10 );
var qty = parseInt( $('input[id^=qty]' , this).val(), 10 );
$('input[id^=linetotal]', this).val(price * qty);
});
So currently I cant get the js to fire that gets the product of the two cells, qty and price. I want to display result in linetotal.
The last part of this would be to display the sum of all linetotals as a grand total in the div grandtotal
Help appreciated as always.
You're only giving the elements a name attribute, but using the id selector ([id^=price]). It's much easier to give them a specific class than having to use that "id starts with" selector. Also, when do you want the line totals to be calculated? And when do you want the grand total to be calculated? On what event(s)?
Here's my interpretation of how it should look:
<table class="order-list">
<thead>
<tr><td>Product</td><td>Price</td><td>Qty</td><td>Total</td></tr>
</thead>
<tbody>
<tr>
<td><input type="text" name="product" /></td>
<td>$<input type="text" name="price" /></td>
<td><input type="text" name="qty" /></td>
<td>$<input type="text" name="linetotal" readonly="readonly" /></td>
<td><a class="deleteRow"> x </a></td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="5" style="text-align: center;">
<input type="button" id="addrow" value="Add Product" />
</td>
</tr>
<tr>
<td colspan="5">
Grand Total: $<span id="grandtotal"></span>
</td>
</tr>
</tfoot>
</table>
And the JS:
$(document).ready(function () {
var counter = 1;
$("#addrow").on("click", function () {
counter++;
var newRow = $("<tr>");
var cols = "";
cols += '<td><input type="text" name="product' + counter + '"/></td>';
cols += '<td>$<input type="text" name="price' + counter + '"/></td>';
cols += '<td><input type="text" name="qty' + counter + '"/></td>';
cols += '<td>$<input type="text" name="linetotal' + counter + '" readonly="readonly"/></td>';
cols += '<td><a class="deleteRow"> x </a></td>';
newRow.append(cols);
$("table.order-list").append(newRow);
});
$("table.order-list").on("change", 'input[name^="price"], input[name^="qty"]', function (event) {
calculateRow($(this).closest("tr"));
calculateGrandTotal();
});
$("table.order-list").on("click", "a.deleteRow", function (event) {
$(this).closest("tr").remove();
calculateGrandTotal();
});
});
function calculateRow(row) {
var price = +row.find('input[name^="price"]').val();
var qty = +row.find('input[name^="qty"]').val();
row.find('input[name^="linetotal"]').val((price * qty).toFixed(2));
}
function calculateGrandTotal() {
var grandTotal = 0;
$("table.order-list").find('input[name^="linetotal"]').each(function () {
grandTotal += +$(this).val();
});
$("#grandtotal").text(grandTotal.toFixed(2));
}
http://jsfiddle.net/QAa35/
In your JS, you weren't using linetotal for the one dynamic input's name. There were other several minor modifications I made. You might as well use <thead>, <tbody> and <tfoot> since you do have those sections in the <table>. Also, I don't think it's a good design to have a new row automatically added when the "product" inputs are changed. That can happen often, and their intent may not be to add a new product...a button is much more friendly. For example, say you type in "asdf" to the first "product" input, then click somewhere. A new row is added. Say you made a typo so you go back and change it to "asd", then click somewhere. Another new row is added. That doesn't seem right.
This function should do the trick:
function updateGrandTotal() {
var prices = [];
$('input[name^="price"]').each(function () {
prices.push($(this).val());
});
var qnts = [];
$('input[name^="qty"]').each(function () {
qnts.push($(this).val());
});
var total = 0;
for(var i = 0; i < prices.length; i++){
total += prices[i] * qnts[i];
}
$('#grandtotal').text(total.toFixed(2));
}
You just need to bind it to the table change event to update the grand total every time an input changes:
$("table.order-list").change(updateGrandTotal);
Here is a working fiddle.

Categories