Trying to figure out problem with table value calculator - javascript

I'm having some trouble on a HTML and JS practice project I'm working on, in where the following function is meant to calculate the total expense cost for the user. The program gave me an error for the date[i], which I then defined as one set of the td elements of the table (which the dates were listed under using the debugger). However, it then gave me another issue with a different function, stating that:
Uncaught DOMException: Failed to execute 'querySelectorAll' on 'Document': '.[object HTMLTableCellElement]' is not a valid selector.
I worry that I'm running in circles for this, and I would like to know what I'm doing wrong. Any help with this would be appreciated.
Pastebin with full code: https://pastebin.com/My3xzyS4
Code most relevant:
function calcClass(sumClass) {
var sumFields = document.querySelectorAll("." + sumClass); //this is the one giving me issues
var sumTotal = 0;
for (var i = 0; i < sumFields.length; i++) {
var itemValue = parseFloat(sumFields[i].value);
if(!isNaN(itemValue)) {
sumTotal += itemValue;
}
}
return sumTotal;
}
function calcExp() {
var expTable = document.querySelectorAll("table#travelExp tr");
for (var i = 0; i < expTable.length; i++) {
var date = document.querySelectorAll("table#travelExp td");
document.getElementById("subtotal"+ [i]).value = formatNumber(calcClass(date[i]), 2);
}
document.getElementById("transTotal").value = formatNumber(calcClass(trans), 2);
document.getElementById("lodgeTotal").value = formatNumber(calcClass(lodge), 2);
document.getElementById("mealTotal").value = formatNumber(calcClass(meal), 2);
document.getElementById("otherTotal").value = formatNumber(calcClass(other), 2);
document.getElementById("expTotal").value = formatUSCurrency(calcClass(sum));
}
function formatNumber(val, decimals) {
return val.toLocaleString(undefined, {minimumFractionDigits: decimals,
maximumFractionDigits: decimals});
}
function formatUSCurrency(val) {
return val.toLocaleString('en-US', {style: "currency", currency: "USD"} );

I see the way you are doing the sums: horizontal, per date, and vertical, per item. Now, your calcClass function takes a class name as input, which is a string. Instead, what you are passing every time is a variable. In the first instance the variable is actually an object. Hence the error: an object cannot be used as a query selector.
Why is it an object?
Why is that an object? Because the last time you used date, it was as a variable to hold the result of document.querySelectorAll("table#travelExp td") which returns a list of objects.
Now, you have a similar problem in the next calls you do to calcClass.
Fix
The fix is actually pretty easy, given the way you have already cleverly structured your table: simply make those strings, as they are meant to be. So, something like this should work.
function calcExp() {
var expTable = document.querySelectorAll("table#travelExp tr");
for (var i = 0; i < expTable.length; i++) {
// var date = document.querySelectorAll("table#travelExp td"); // likely not needed
document.getElementById("subtotal" + i).value = formatNumber(calcClass('date' + i), 2);
}
document.getElementById("transTotal").value = formatNumber(calcClass('trans'), 2);
document.getElementById("lodgeTotal").value = formatNumber(calcClass('lodge'), 2);
document.getElementById("mealTotal").value = formatNumber(calcClass('meal'), 2);
document.getElementById("otherTotal").value = formatNumber(calcClass('other'), 2);
document.getElementById("expTotal").value = formatUSCurrency(calcClass('sum'));
}

The reason you have the error is that you're putting an element from querySelectorAll but your calcClass function receives a string argument and query again with querySelectorAll. It seems like you need to pass 'date'+[i] to calcClass and let the function partial(daily) sum of each costs.
After that, I've countered another error "<a class='gotoLine' href='#352:54'>352:54</a> Uncaught TypeError: Cannot set property 'value' of null". You're iterating expTable.length times but only has 6 rows. I put 6 directly to the for loop and you need to replace this number.
"use strict";
/*
New Perspectives on HTML5, CSS3, and JavaScript 6th Edition
Tutorial 13
Case Problem 2
Author: 4terrabytes
Date: 7/27/2020
Filename: dl_expenses.js
Function List
=============
validateSummary()
Validates the data entry in the summary field.
calcClass(sumClass)
Sums up all of the data values for elements of the sumClass class.
calcExp()
Calculates the travel expenses from all categories and dates.
formatNumber(val, decimals)
Formats the value, "val" to the number of decimals indicated
by "decimals", adding thousands separators.
formatUSCurrency(val)
Formats the value, "val", as U.S. currency.
*/
//create an anon function
window.addEventListener("load", function() {
var changingCells = document.querySelectorAll("table#travelExp input.sum");
for(var i = 0; i < changingCells.length; i++) {
changingCells[i].onchange = calcExp;
}
document.getElementById("submitButton").onclick = validateSummary;
});
function validateSummary(){
var summary = document.getElementById("summary");
if (summary.validity.valueMissing) {
summary.setCustomValidity("You must include a summary of the trip in your report.");
}
else {
summary.setCustomValidity("");
}
}
function calcClass(sumClass) {
var sumFields = document.querySelectorAll("." + sumClass);
var sumTotal = 0;
for (var i = 0; i < sumFields.length; i++) {
var itemValue = parseFloat(sumFields[i].value);
if(!isNaN(itemValue)) {
sumTotal += itemValue;
}
}
return sumTotal;
}
function calcExp() {
var expTable = document.querySelectorAll("table#travelExp input.sum");
for (var i = 0; i < 6; i++) {
var date = document.querySelectorAll("table#travelExp td");
document.getElementById("subtotal"+ [i]).value = formatNumber(calcClass("date"+[i]), 2);
}
document.getElementById("transTotal").value = formatNumber(calcClass("trans"), 2);
document.getElementById("lodgeTotal").value = formatNumber(calcClass("lodge"), 2);
document.getElementById("mealTotal").value = formatNumber(calcClass("meal"), 2);
document.getElementById("otherTotal").value = formatNumber(calcClass("other"), 2);
document.getElementById("expTotal").value = formatUSCurrency(calcClass("sum"));
}
function formatNumber(val, decimals) {
return val.toLocaleString(undefined, {minimumFractionDigits: decimals,
maximumFractionDigits: decimals});
}
function formatUSCurrency(val) {
return val.toLocaleString('en-US', {style: "currency", currency: "USD"} );
}
//HTML Code
<!DOCTYPE html>
<html lang="en">
<head>
<!--
New Perspectives on HTML5, CSS3, and JavaScript 6th Edition
Tutorial 13
Case Problem 2
Travel Expense Report
Author: 4terrabytes
Date: 7/27/2020
Filename: dl_expense.html
-->
<title>DeLong Enterprises Expense Report</title>
<meta charset="utf-8" />
<link href="dl_base.css" rel="stylesheet" />
<link href="dl_layout.css" rel="stylesheet" />
<script src="dl_expense.js" async></script>
</head>
<body>
<header>
<nav class="horizontal">
<ul>
<li>Home</li>
<li>Policies</li>
<li>Reports</li>
<li>Employment</li>
<li>Financial</li>
<li>Insurance</li>
<li>Accounts</li>
</ul>
</nav>
<img src="dl_logo.png" alt="DeLong Enterprises" id="logoImg" />
</header>
<section>
<form name="expReport" id="expReport" method="post" action="dl_valid.html">
<table id="travelSummary">
<tr>
<th>Trip Summary<span>*</span></th>
</tr>
<tr>
<td>
<textarea id="summary" name="summary" required></textarea>
</td>
</tr>
</table>
<aside>
<h1>Expense Report</h1>
<p>Form: 2CEXP15<br />
* --- Required Field
</p>
<p>Send Report To:<br />
Debbie Larson<br />
Personnel Dept.<br />
Rm. 3801<br />
Ext. 1250
</p>
</aside>
<table id="empInfo">
<tr>
<th>Last Name<span>*</span></th>
<th>First Name<span>*</span></th>
<th>M.I.</th>
<th>Account<span>*</span></th>
<td><input type="text" name="accID" id="accID" pattern="^ACT\d{6}$" placeholder="ACTnnnnnn" required /></td>
</tr>
<tr>
<td><input type="text" name="lname" id="lname" required /></td>
<td><input type="text" name="fname" id="fname" required /></td>
<td><input type="text" name="init" id="init" required /></td>
<th>Department<span>*</span></th>
<td><input type="text" name="deptID" id="deptID" pattern="^DEPT\d{4,6}$" required placeholder="DEPTnnnnnn" /></td>
</tr>
<tr>
<th>Social Security Number<span>*</span></th>
<td colspan="2"><input type="text" name="ssn" id="ssn" pattern="^\d{3}-\d{2}-\d{4}$" required placeholder="nnn-nn-nnnn" /></td>
<th>Project<span>*</span></th>
<td><input type="text" name="projID" id="projID" pattern="^PROJ-[a-z]{2}-\d{3}$" required placeholder="PROJ-xx-ddd" /></td>
</tr>
</table>
<table id="travelExp">
<thead>
<tr>
<th>Travel Date</th>
<th>Air & Trans</th>
<th>Lodging</th>
<th>Meals & Tips</th>
<th>Other</th>
<th>TOTAL</th>
</tr>
</thead>
<tfoot>
<tr>
<th>SUMMARY</th>
<td><input type="text" name="transTotal" id="transTotal" readonly /></td>
<td><input type="text" name="lodgeTotal" id="lodgeTotal" readonly /></td>
<td><input type="text" name="mealTotal" id="mealTotal" readonly /></td>
<td><input type="text" name="otherTotal" id="otherTotal" readonly /></td>
<td><input type="text" name="expTotal" id="expTotal" readonly /></td>
</tr>
</tfoot>
<tbody>
<tr>
<td>
<input type="date" name="tDate0" id="tDate0" class="tDate" />
</td>
<td>
<input type="text" name="trans0" id="trans0" class="trans date0 sum" />
</td>
<td>
<input type="text" name="lodge0" id="lodg0" class="lodge date0 sum" />
</td>
<td>
<input type="text" name="meal0" id="meal0" class="meal date0 sum" />
</td>
<td>
<input type="text" name="other0" id="other0" class="other date0 sum" />
</td>
<td>
<input type="text" name="subtotal0" id="subtotal0" class="subtotal" readonly />
</td>
</tr>
<tr>
<td>
<input type="date" name="tDate1" id="tDate1" class="tDate" />
</td>
<td>
<input type="text" name="trans1" id="trans1" class="trans date1 sum" />
</td>
<td>
<input type="text" name="lodge1" id="lodg1" class="lodge date1 sum" />
</td>
<td>
<input type="text" name="meal1" id="meal1" class="meal date1 sum" />
</td>
<td>
<input type="text" name="other1" id="other1" class="other date1 sum" />
</td>
<td>
<input type="text" name="subtotal1" id="subtotal1" class="subtotal" readonly />
</td>
</tr>
<tr>
<td>
<input type="date" name="tDate2" id="tDate2" class="tDate" />
</td>
<td>
<input type="text" name="trans2" id="trans2" class="trans date2 sum" />
</td>
<td>
<input type="text" name="lodge2" id="lodg2" class="lodge date2 sum" />
</td>
<td>
<input type="text" name="meal2" id="meal2" class="meal date2 sum" />
</td>
<td>
<input type="text" name="other2" id="other2" class="other date2 sum" />
</td>
<td>
<input type="text" name="subtotal2" id="subtotal2" class="subtotal" readonly />
</td>
</tr>
<tr>
<td>
<input type="date" name="tDate3" id="tDate3" class="tDate" />
</td>
<td>
<input type="text" name="trans3" id="trans3" class="trans date3 sum" />
</td>
<td>
<input type="text" name="lodge3" id="lodg3" class="lodge date3 sum" />
</td>
<td>
<input type="text" name="meal3" id="meal3" class="meal date3 sum" />
</td>
<td>
<input type="text" name="other3" id="other3" class="other date3 sum" />
</td>
<td>
<input type="text" name="subtotal3" id="subtotal3" class="subtotal" readonly />
</td>
</tr>
<tr>
<td>
<input type="date" name="tDate4" id="tDate4" class="tDate" />
</td>
<td>
<input type="text" name="trans4" id="trans4" class="trans date4 sum" />
</td>
<td>
<input type="text" name="lodge4" id="lodg4" class="lodge date4 sum" />
</td>
<td>
<input type="text" name="meal4" id="meal4" class="meal date4 sum" />
</td>
<td>
<input type="text" name="other4" id="other4" class="other date4 sum" />
</td>
<td>
<input type="text" name="subtotal4" id="subtotal4" class="subtotal" readonly />
</td>
</tr>
<tr>
<td>
<input type="date" name="tDate5" id="tDate5" class="tDate" />
</td>
<td>
<input type="text" name="trans5" id="trans5" class="trans date5 sum" />
</td>
<td>
<input type="text" name="lodge5" id="lodg5" class="lodge date5 sum" />
</td>
<td>
<input type="text" name="meal5" id="meal5" class="meal date5 sum" />
</td>
<td>
<input type="text" name="other5" id="other5" class="other date5 sum" />
</td>
<td>
<input type="text" name="subtotal5" id="subtotal5" class="subtotal" readonly />
</td>
</tr>
</tbody>
</table>
<input id="submitButton" type="submit" value="Submit Report" />
</form>
</section>
<footer>
<nav class="vertical">
<ul>
<li>Travel Expenses</li>
<li>Information Change</li>
<li>Time Off Request</li>
<li>Paystubs</li>
<li>Health Insurance</li>
<li>Forms/Requests</li>
<li>Team Contacts</li>
<li>Reimbursements</li>
<li>Grievances</li>
<li>Staff Directory</li>
</ul>
</nav>
<p>DeLong Enterprises © 2018 All Rights Reserved</p>
</footer>
</body>
</html>

Related

My total_final value not working and Button too

My first problem is my for loop not working, I'm trying to get my final total value from the two rows total by adding both of them up. And my second problem is when I press my button it's not executing my function calculateTotal().
been learning javascript for around 4 weeks and I guess I still count as a beginner and I'm not very good with javascript
function calculateTotal() {
// first row //
var Unit_Price_1 = document.getElementById('Unit Price_1').value;
var Quantity_1 = document.getElementById('Quantity_1').value;
var Total_1 = document.getElementById('Total_1')
var Total_Amount_1 = Unit_Price_1 * Quantity_1;
Total_1.value = Total_Amount_1
// Second row //
var Unit_Price_2 = document.getElementById('Unit Price_2').value;
var Quantity_2 = document.getElementById('Quantity_2').value;
var Total_2 = document.getElementById('Total_2')
var Total_Amount_2 = Unit_Price_2 * Quantity_2;
Total_2.value = Total_Amount_2
var arr = document.getElementsByName('total');
var total = 0;
for (var i = 0; i < arr.length; i++) {
if (parseInt(arr[i].value))
total += pareseInt(arr[i].value);
}
document.getElementById('total_final').value = total;
}
<table>
<thead>
<tr>
<th>Unit Price</th>
<th>Quantity</th>
<th>Total</th>
</tr>
</thead>
<tbody>
<!---------------- ROW 1 ------------------>
<td>
<input type="number" name="unit price" placeholder="0.00" id="Unit Price_1" oninput="calculateTotal()" />
</td>
<td>
<input type="number" name="Quality" placeholder="0" id="Quantity_1" oninput="calculateTotal()" />
</td>
<td>
<input required type="number" name="total" value="0.00" readonly="readonly" id="Total_1" />
</td>
</tr>
<!---------------- ROW 2 ------------------>
<td>
<input type="number" name="unit price" placeholder="0.00" id="Unit Price_2" onkeyup="calculateTotal()" />
</td>
<td>
<input type="number" name="Quality" placeholder="0" id="Quantity_2" onkeyup="calculateTotal()" />
</td>
<td>
<input required type="number" name="total" value="0.00" readonly="readonly" id="Total_2" />
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="5">
<input type="button" style="background-color: white" value="Calculate Grand Total Price" id="click me" onclick="calculateTotal()" />
</td>
<td colspan="2">
<input type="number" name="total_final" id="total_final" value="0.00" style="font-size: 18px; background-color: silver" readonly="readonly" />
</td>
</tr>
</tfoot>
</table>
There is a typo in total += pareseInt(arr[i].value); It is parseInt.
I ran your code and it is working fine.

Jquery Form Calculation not aligning

I have trying to get this jQuery math to work with my form which I got the snippet to work fine but when transferring across to the required form I can't get it aligned to run the math required.
any pointers to where I am going wrong.
<script type="text/javascript" src="jquery-1.12.3.js"></script>
<script>
jQuery(function($) {
$(".Qty1, .TradePrice1").change(function() {
var total = 0;
$(".Qty1").each(function() {
var self = $(this),
TradePrice1 = self.next(".TradePrice1"),
subtotal = parseInt(self.val(), 10) * parseFloat(TradePrice1.val(), 10);
total += (subtotal || 0);
});
$("#total1").val(total);
});
});
</script>
<tr>
<th><div align="center">
<input type='text' name='F01u1' id='F01u1' />
</th>
<td>
<input type='text' name='Model1' id='Model1' />
</td>
<td>
<input type='text' name='Description1' id='Description1' />
</td>
<td>
<input type="text" name='TradePrice1' id='TradePrice1' />
</td>
<th>
<input type="text" name='Qty1' id='Qty1' />
</th>
<td>
<input type='text' name='Total1' id='Total1' />
</div></td>
</tr>
You have quite a few issues in your code.
the inputs will have duplicate id attributes which is invalid. You should use classes instead
you have some extraneous div elements which aside from being not needed, aren't opened or closed properly.
parseFloat() only takes a single parameter
the total field is not readonly so it can be amended by anyone, to any value desired.
your code works out the total for all rows and places it at the end of each individual row
.TradePrice1 is not a sibling of .Qty1 hence it will never be found from a next() call
With all that in mind you can massively improve your code. Try this:
$(".qty, .tradeprice").change(function() {
var total = 0;
$(".qty").each(function() {
var $qty = $(this),
$row = $qty.closest('tr'),
$tradePrice = $row.find('.tradeprice'),
$subtotal = $row.find('.subtotal');
subtotal = parseInt($qty.val(), 10) * parseFloat($tradePrice.val());
total += subtotal;
$subtotal.val(subtotal);
});
$('.total').val(total);
}).change();
input {
width: 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<th>
<input type='text' name='F01u1' class='F01u1' />
</th>
<td>
<input type='text' name='Model' class='model' />
</td>
<td>
<input type='text' name='Description' class='description' />
</td>
<td>
<input type="text" name='TradePrice' class='tradeprice' value="100" />
</td>
<th>
<input type="text" name='Qty' class='qty' value="2" />
</th>
<td>
<input type='text' name='Total' class='subtotal' readonly="true" />
</td>
</tr>
<tr>
<th>
<input type='text' name='F01u1' class='F01u1' />
</th>
<td>
<input type='text' name='Model' class='model' />
</td>
<td>
<input type='text' name='Description' class='description' />
</td>
<td>
<input type="text" name='TradePrice' class='tradeprice' value="123" />
</td>
<th>
<input type="text" name='Qty' class='qty' value="5" />
</th>
<td>
<input type='text' name='Total' class='subtotal' readonly="true" />
</td>
</tr>
<tr>
<td colspan="6" align="right">
Total:
<input type='text' name='Total' class='total' readonly="true" />
</td>
</tr>
</table>
Note that the default values are purely for demonstration purposes and can be removed if needed.

jQuery- Dynamically multiply input values of table rows with different id

Dynamically adding table rows using below code. User ID is appended for input id.
var selResId = jQuery('#grid').jqGrid('getGridParam', 'selarrrow');
var j=1;
for (var i=0, il=selResId.length; i < il; i++) {
var name = jQuery('#grid').jqGrid('getCell', selResId[i], 'USER_NAME');
$('#addr'+j).html("<td style='text-align:center;'>"+name+"</td><td><input id='hours_"+selResId[i]+"' value='80' type='text' readonly /></td><td><input id='rate_"+selResId[i]+"' type='text' /></td><td><input name='markup_"+selResId[i]+"' type='text'/></td><td><input name='totalcost_"+selResId[i]+"' type='text' readonly></td>");
$('#resource_table').append('<tr id="addr'+(j+1)+'"></tr>');
j++;
}
}
HTML Generated
<tr id="addr1">
<td>John Doe</td>
<td><input type="text" readonly="" value="80" id="hours_10"></td>
<td><input type="text" value="" id="rate_10"></td>
<td><input type="text" value="" id="markup_10"></td>
<td><input type="text" readonly="" value="" id="totalcost_10"></td>
</tr>
<tr id="addr2">
<td>Foo User</td>
<td><input type="text" readonly="" value="80" id="hours_11"></td>
<td><input type="text" value="" id="rate_11"></td>
<td><input type="text" value="" id="markup_11"></td>
<td><input type="text" readonly="" value="" id="totalcost_11"></td>
</tr>
How do I multiply input values for hours, rate and markup and show it under total cost input using below formula. The event could be keyup.
Initially, totalcost = hours * rate
Case 1: If markup (%) > 0, for eg: 10%, then markup_cost = (hours * rate * markup) / 100
totalcost = (hours * rate) + markup_cost
Case 2: If markup (%) < 0, for eg: -10%, then markup_cost = (hours * rate * markup) / 100
totalcost = (hours * rate) - markup_cost
Try to use starts with selector like,
$(function(){
function setTotalCost(n){
var h=Number($('#hours_'+n).val()),
m=Number($('#markup_'+n).val()), // taking 0 if empty
r=Number($('#rate_'+n).val());
$('#totalcost_'+n).val(h*m*r);
}
$('[id^="rate_"]').on('keyup',function(){
var n = this.id.replace('rate_','');// get the number
setTotalCost(n);
});
$('[id^="markup_"]').on('keyup',function(){
var n = this.id.replace('markup_','');// get the number
setTotalCost(n);
});
});
$(function(){
function setTotalCost(n){
var h=Number($('#hours_'+n).val()),
m=Number($('#markup_'+n).val()), // taking 0 if empty
r=Number($('#rate_'+n).val());
$('#totalcost_'+n).val(h*m*r);
}
$('[id^="rate_"]').on('keyup',function(){
var n = this.id.replace('rate_','');// get the number
setTotalCost(n);
});
$('[id^="markup_"]').on('keyup',function(){
var n = this.id.replace('markup_','');// get the number
setTotalCost(n);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr id="addr1">
<td>John Doe</td>
<td>
<input type="text" readonly="" value="80" id="hours_10">
</td>
<td>
<input type="text" value="" id="rate_10">
</td>
<td>
<input type="text" value="" id="markup_10">
</td>
<td>
<input type="text" readonly="" value="" id="totalcost_10">
</td>
</tr>
<tr id="addr2">
<td>Foo User</td>
<td>
<input type="text" readonly="" value="80" id="hours_11">
</td>
<td>
<input type="text" value="" id="rate_11">
</td>
<td>
<input type="text" value="" id="markup_11">
</td>
<td>
<input type="text" readonly="" value="" id="totalcost_11">
</td>
</tr>
</table>

Calculating Subtotals for Category Sections Using Class Names

I'm working on a project that is based on an Excel spreadsheet, where I need to calculate budgets, etc. There are various categories in my table, and I need to calculate the subtotal of each category. Here's a screenshot to make it more clear:
http://i.imgur.com/loyLbW7.png
My problem is, I'm not sure how to calculate the subtoal for each category. Right now, I have $('.subcat100 .budget').each(function(). The class "subcat100" is attached to the tr and changes for each category section (subcat100, subcat200, subcat300, etc.). The numerical value is based off the sub category number stored in database. How would I pull all of these classes and iterate through them?
jQuery:
$(document).ready(function() {
$('input[name="txtQuantity[]"],input[name="txtUnitCost[]"]').change(function(e) {
var budget = 0;
var $row = $(this).parent().parent();
var quanity = $row.find('input[name="txtQuantity[]"]').val();
var unitcost = $row.find('input[name="txtUnitCost[]"]').val();
budget = parseFloat(quanity * unitcost);
var decimal = budget.toFixed(2);
$row.find('.budget').val(decimal);
var sum = 0;
$('.subcat100 .budget').each(function() {
var budgets = $(this).val();
console.log(budgets);
if (IsNumeric(budgets)) {
sum += parseFloat(budgets, 10);
}
});
$('.subcat100 .budgetsubtotal').val(sum);
});
function IsNumeric(input) {
return (input - 0) == input && input.length > 0;
}
});
HTML:
<table>
<tbody>
<tr class="subcat100">
<td>
<span name="txtItemCode[]"><strong>100</strong></span>
</td>
<td colspan="7">
<span name="txtSubCategoryName[]" class="100"><strong>Land Purchase Costs</strong></span>
</td>
</tr>
<tr class="subcat100">
<td>
<input type="text" name="txtSubItemCode[]" size="10" readonly="readonly" value="101">
</td>
<td>
<input type="text" name="txtItem[]" size="50" readonly="readonly" value="Purchase price">
</td>
<td>
<input type="text" name="txtUnit[]" size="10" value="">
</td>
<td>
<input type="text" name="txtQuantity[]" class="integer" size="10" value="1">
</td>
<td>
<input type="text" name="txtUnitCost[]" class="monetary" size="10" value="299.99">
</td>
<td>
<input type="text" name="txtBudget[]" class="monetary budget" size="10" readonly="readonly" value="299.99">
</td>
<td>
<input type="text" name="txtActual[]" class="monetary" size="10" value="249.99">
</td>
<td>
<input type="text" name="txtDifference[]" class="monetary difference" size="10" readonly="readonly" value="50.00">
</td>
</tr>
<tr class="subcat100">
<td>
<input type="text" name="txtSubItemCode[]" size="10" readonly="readonly" value="110">
</td>
<td>
<input type="text" name="txtItem[]" size="50" readonly="readonly" value="Realtor's fees">
</td>
<td>
<input type="text" name="txtUnit[]" size="10" value="">
</td>
<td>
<input type="text" name="txtQuantity[]" class="integer" size="10" value="">
</td>
<td>
<input type="text" name="txtUnitCost[]" class="monetary" size="10" value="">
</td>
<td>
<input type="text" name="txtBudget[]" class="monetary budget" size="10" readonly="readonly" value="">
</td>
<td>
<input type="text" name="txtActual[]" class="monetary" size="10" value="">
</td>
<td>
<input type="text" name="txtDifference[]" class="monetary difference" size="10" readonly="readonly" value="">
</td>
</tr>
<tr class="subcat100">
<td>
<input type="text" name="txtSubItemCode[]" size="10" readonly="readonly" value="120">
</td>
<td>
<input type="text" name="txtItem[]" size="50" readonly="readonly" value="Due diligence">
</td>
<td>
<input type="text" name="txtUnit[]" size="10" value="">
</td>
<td>
<input type="text" name="txtQuantity[]" class="integer" size="10" value="15">
</td>
<td>
<input type="text" name="txtUnitCost[]" class="monetary" size="10" value="45.00">
</td>
<td>
<input type="text" name="txtBudget[]" class="monetary budget" size="10" readonly="readonly" value="675.00">
</td>
<td>
<input type="text" name="txtActual[]" class="monetary" size="10" value="700.00">
</td>
<td>
<input type="text" name="txtDifference[]" class="monetary difference" size="10" readonly="readonly" value="-25.00">
</td>
</tr>
<tr class="subcat100">
<td colspan="5">
<span><strong>Subtotal</strong></span>
</td>
<td>
<input type="text" name="txtSubTotalBudget[]" class="budgetsubtotal" size="10" readonly="readonly" value="">
</td>
<td>
<input type="text" name="txtSubTotalActual[]" class="actualsubtotal" size="10" readonly="readonly" value="">
</td>
<td>
<input type="text" name="txtSubTotalDifference[]" class="differencesubtotal" size="10" readonly="readonly" value="">
</td>
</tr>
</tbody>
</table>
Well, I ended up doing this:
var itemcodes = <?php echo json_encode($arrItemCodes);?>;
$('input[name="txtQuantity[]"],input[name="txtUnitCost[]"]').change(function(e) {
var budget = 0;
var $row = $(this).parent().parent();
var quanity = $row.find('input[name="txtQuantity[]"]').val();
var unitcost = $row.find('input[name="txtUnitCost[]"]').val();
budget = parseFloat(quanity * unitcost);
$row.find('.budget').val(budget.toFixed(2));
$.each(itemcodes, function(intIndex, objValue) {
var sum = 0;
$('.subcat' + objValue + ' .budget').each(function() {
var budgets = $(this).val();
console.log(budgets);
if (IsNumeric(budgets)) {
sum += parseFloat(budgets, 10);
}
});
$('.subcat' + objValue + ' .budgetsubtotal').val(sum.toFixed(2));
});
});
Open to other suggestions!

Javascript Calculation - If Statement

I would like to display a different option for different choices.
If MenuNo1 (textinput) equal either 1,2,3,4 or 5 - then the value of menuPrice1 should be R70.00.
If MenuNo1(textinput) equal either 8,9,12 - then the value of menuPrice1 should be R85.00.
If MenuNo1 (textinput) equal 11 - then the value of menuPrice1 should be R105.00.
I have tried doing it this way: However nothing appears in the MenuPrice1 field? There are also no errors in the console.
function calcMenu(form) {
var MenuPrice1 = (+form.MenuPrice1.value);
var MenuNo1 = (+form.MenuNo1.value);
if ([1,2,3,4,5].indexOf(+form.MenuNo1.value) != -1) {
MenuPrice1.value = "70";
}
else if ([8,9,12].indexOf(+form.MenuNo1.value) != -1) {
MenuPrice1.value = "85";
}
else if (+form.MenuNo1.value == 11) {
MenuPrice1.value = "105";
}
}
HTML
<form id="quote" action="" method="get">
<script type="text/javascript">
// <![CDATA[
jQuery(document).ready(function($) {
jQuery('#quote').change(function() {
doTotal(this)
});
});
// ]]>
</script>
<script type="text/javascript">
// <![CDATA[
jQuery(document).ready(function($) {
jQuery('#quote').change(function() {
calcMenu(this)
});
});
// ]]>
</script>
<table width="532" border="1" cellspacing="1" cellpadding="0.5">
<tbody>
<tr>
<th scope="col" width="70">
<div align="center">
Date
</div></th>
<th scope="col" width="158">
<div align="center">
Amount of Delegates ½ Day Conference # R 240 pp
</div></th>
<th width="112">
<div align="center">
Amount of Delegates Full Day Conference # R 260 pp
</div></th>
<th width="112">
<div align="center">
Menu No
</div></th>
<th width="112">
<div align="center">
Price pp for Menu (1-7: R70, 8-10 R85, 11: R105, 12: R85)
</div></th>
<th width="134">
<div align="center">
Total for the day
</div></th>
</tr>
<tr>
<td>
<div align="center">
<input type="text" name="date1" size="15" />
</div></td>
<td>
<div align="center">
<input type="text" name="halfday1" size="15" maxlength="10" />
</div></td>
<td>
<div align="center">
<input type="text" name="fullday1" size="15" />
</div></td>
<td>
<div align="center">
<input type="text" name="MenuNo1" size="15" />
</div></td>
<td>
<div align="center">
<input type="text" name="MenuPrice1" size="15" />
</div></td>
<td>
<div align="center">
<input type="text" name="total1" size="15" />
</div></td>
</tr>
<tr>
<td>
<div align="center">
<input type="text" name="date2" size="15" />
</div></td>
<td>
<div align="center">
<input type="text" name="halfday2" size="15" />
</div></td>
<td>
<div align="center">
<input type="text" name="fullday2" size="15" />
</div></td>
<td>
<div align="center">
<input type="text" name="MenuNo2" size="15" />
</div></td>
<td>
<div align="center">
<input type="text" name="MenuPrice2" size="15" />
</div></td>
<td>
<div align="center">
<input type="text" name="total2" size="15" />
</div></td>
</tr>
<tr>
<td>
<div align="center">
<input type="text" name="date3" size="15" />
</div></td>
<td>
<div align="center">
<input type="text" name="halfday3" size="15" />
</div></td>
<td>
<div align="center">
<input type="text" name="fullday3" size="15" />
</div></td>
<td>
<div align="center">
<input type="text" name="MenuNo3" size="15" />
</div></td>
<td>
<div align="center">
<input type="text" name="MenuPrice3" size="15" />
</div></td>
<td>
<div align="center">
<input type="text" name="total3" size="15" />
</div></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
</form>
You have var MenuPrice1 = (+form.MenuPrice1.value); and are doing MenuPrice1.value = later on.
Also there is a cleaner way to do this that would make it easier to maintain in the future too.
Fiddle: http://jsfiddle.net/8q7Fh/3
var prices = [
{
values: [1,2,3,4,5],
price: 'R70.00'
},
{
values: [8,9,12],
price: 'R85.00'
},
{
values: [11],
price: 'R105.00'
}
];
function calcMenu(form)
{
var i, searchValue = parseInt(form.MenuNo1.value);
form.MenuPrice1.value = '';
for (i in prices)
{
if ($.inArray(searchValue, prices[i].values) != -1)
{
form.MenuPrice1.value = prices[i].price;
}
}
}
Notes: You are currently missing prices for when the values are either 6, 7 and 10. For now I've set it so that it will clear the value in the MenuPrice if it cannot find a definite price. Something to think about!

Categories

Resources