[Webinar] Streamline your web hosting managementRegister Today

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1450
  • Last Modified:

jQuery Addition & Multiplication

I have a form in which a user will type in the unit price, tax and shipping of an item, then begin to break down quantities in which will be charged.

What I'd like to have happen is the Unit Price, Tax, & Shipping would get added together, then as a user is adding distributions, have the Unit Price multiply by the Qty in each of the fields.

The result of QTY * UNIT PRICE would store in the Amount column in the far right.

The Sum of UNIT PRICE + TAX + SHIPPING would go into the Purchase Total box at the bottom of the form, and as quantities are being added, have the Purchase Total adjust to add the result of QTY * UNIT PRICE.

There is one caveat in this whole thing, which is a user can add as many rows to that Distributions table as necessary.

A screenshot is attached with the table layout to help further understand what I'm trying to do.

I've got some functions that appear to work right, I think I just need some of the jQuery tweaked, but willing to change whatever is necessary to get this done.

Thanks in advance!


<form id="createDistribution" name="createDistribution" method="POST" enctype="multipart/form-data" action="">
		<input type="hidden" name="vendoracct" value = "<?=$vendorid?>">
		<div id="container" class="shadow">
			<div id="row">
				<div id="left">
					<strong>Description:</strong>
				</div>
				<div id="defaultdiv">
					<div id="right">
						<input type="text" class="fieldclasssm" name="linedescr[]" value = "<? if (!empty($_POST['custRef'])) { echo "value='".safeData($_POST['custRef'])."'"; }?>" size="113" />
					</div>
				</div>
			</div>
			<div id="row">
				<div id="left">
					<strong>Unit Price:</strong>
				</div>
				<div id="defaultdiv">
					<div id="right" class="total">
						<input type="text" class="multiplier fieldclasssm" name="unitPrice" id="unitPrice"  size="10"/>
					</div>
				</div>
			</div>
			<div id="row">
				<div id="left">
					<strong>Tax:</strong>
				</div>
				<div id="defaultdiv">
					<div id="right" class="total">
						<input type="text" class="multiplier fieldclasssm" name="tax" id="tax" size="10"/>
					</div>
				</div>
			</div>
			<div id="row">
				<div id="left">
					<strong>Shipping:</strong>
				</div>
				<div id="defaultdiv">
					<div id="right" class="total">
						<input type="text" class="fieldclasssm" name="shipping" id="shipping" size="10"/>
					</div>
				</div>
			</div>
			<div id="row">
				<div id="left">
					<strong>Distributions:</strong>
				</div>
				<div id="defaultdiv">
					<div id="right">
						<table border="0" width="800px" cellspacing="0" cellpadding="0" id = "distributions">
							<thead>
								<tr>
									<th class="colheader" width="65px">Qty</th>
									<th class="colheader" width="325px">Nominal Code</th>
									<th class="colheader" width="300px">Depot</th>
									<th class="colheader" width="100px">Amount</th>
									<th class="colheader" width="110px"><span class="boldblacklinks"><a href="#" id="add">[Add +]</a></span></th>
								</tr>
							</thead>
							<tbody class="lineBdy">
								<tr id="line_1" class="spacer">
									<td><input type="text" class="fieldclasssm" id="qty" name="distQty[]" size="5" /></td>
									<td><input type="text" class="nominal fieldclasssm" name="distNomCode[]" size="53" /></td>
									<td><input type="text" class="depot fieldclasssm" name="distDepot[]" size="50" /></td>
									<td><input type="text" class="fieldclasssm" id="distAmount[]" name="lineTotal" size="10" disabled />
									</td>
									<td>&nbsp;</td>
								</tr>
							</tbody>
						</table>
						<input type="hidden" id="items" name="items" value="1" /> 
						<input type="hidden" id="numRows" value= "<?=$numRows?>" />
						<br /><br />
					</div>
				</div>
			</div>
			<div id="row">
				<div id="left">
					<strong>Purchase Total:</strong>
				</div>
				<div id="defaultdiv">
					<div id="right" class="total">
						<input type="text" class="money fieldclasssm" disabled id="poTotal" size="10"/>
					</div>
				</div>
			</div>
			<div align="center"><br /><input type="submit" name="saveClose" class="btn" value = "Save & Finish Distribution"> <input type="submit" class="btn" name="saveCont" value="Save & Add New Item"><br /><br /></div>
		</div>
	</form>
	<br /><br /><br /><div align="center"><hr width="75%"></div><br /><br />	
		
	<?php
		
	//Summary Info
	$getItems = mysql_query("SELECT itemid, description, qty, amount, shipping, tax FROM pr_po_items WHERE poNumber = '".$poNum."'");

	if(mysql_num_rows($getItems) > 0)
		{ ?>
		
		<input type="hidden" name="vendoracct" value = "<?=$vendorid?>">
		<div id="container" class="shadow">
			<div id="row">
				<div id="left">
					<strong>Distributions:</strong>
				</div>
				<div id="defaultdiv">
					<div id="right">
						<span class="boldgreenlinks"><a href="lineItems.php" class="iframe">Create Item & Distributions</span></a>
					</div>
				</div>
			</div>
		</div>	
	<?	}
	
	else
		{
		echo '<div align="center"><span class="errormessagered"><strong>No items have been found for Purchase Order #'.$poNum.'.</span></div>';
		}
	break;
	}
?>


<link rel="stylesheet" type="text/css" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.9.2/themes/base/jquery-ui.css" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.9.2/jquery-ui.min.js"></script>
<script type="text/javascript">

$(function () 
	{
	/*Used for if Billing address changes, as of now, this will never change though.
	$("#usedefaultbill").click(function () {
        $("#newdivbill").hide();
     });
    $("#usealternatebill").click(function () {
        $("#newdivbill").show();
    });
	*/
	
	//Show extra fields if shipping location is not a warehouse.
	$("#usedefaultship").click(function () {
        $("#newdivship").hide();
     });
    $("#usealternateship").click(function () {
        $("#newdivship").show();
    });

	//Hide Customer Reference by default, show with condition.
	$("#poType").change(function()
		{
		$("#showcustref").hide();
			var chosenValue = $("#poType").val();
			if (chosenValue == "5" || chosenValue == "3" ) 
				{
				$("#showcustref").show();
				}  
		});

	//This is the autocomplete & autofill for shipping company search fields.
	$("#compname").autocomplete(
		{
		source: "autocomplete.php",
		minLength: 3,
		select: function(event, ui) 
			{
			event.preventDefault();
			$("#compid").val(ui.item.id);
			$("#compname").val(ui.item.label);
			$(':text[name=shipCompName]').val(ui.item.label);
			$(':text[name=shipAddress]').val(ui.item.address);
			$(':text[name=shipCity]').val(ui.item.town);
			$(':text[name=shipState]').val(ui.item.state);
			$(':text[name=shipZip]').val(ui.item.postcode);
			}
		});

	/*Not sure this is needed anymore.
	$("#compid").change( function () {
	  $("#submit").trigger('click');
	}); 
	*/

	//Add new table row & clone nominal
	$('#add').on('click', function(){
	   DistributionAddLine();
	});


	function DistributionAddLine(){
		 var lastID = $('tr[id*="line_"]').length,    
			 newTds = $('tr[id="line_' + lastID + '"] td').clone(),
			 newRow = document.createElement('tr');
	   
		// add new id and class to row, append cloned tds
		$(newRow)
			.attr('id', 'line_' + (lastID + 1 ))
			.attr('class', 'spacer')
			.append(newTds)
		;
		
		//empty out the fields, except the one you want to keep populated
		$(newRow).find('input').not(':eq(1)').val('');
		
		//add the new row to the table body
		$('tbody.lineBdy').append(newRow);
		
	}
		
	//Autocomplete nominal & depot fields on first row.
	$('.nominal').autocomplete({source:'suggestNominal.php', minLength:2});
	$('.depot').autocomplete({source:'suggestDepot.php', minLength:2});
	

	//Multiply Unit Price & Quantity
	
	// $('#poTotal').css('color', '#be0711', 'font-weight', '900')
	// $('input').blur(function() {
	// var price = $('#price').val()	
	// var quantity = $('#qty').val()	
	// var total = price * quantity;
		// if (!isNaN(total)) {
		// $('#poTotal').attr('value', total)
		// } else {
		// alert('Oops Error! Please only numbers')
		// }
	// });	


	//Add Unit Price + Shipping + Tax
	$('#poTotal').css('color', '#be0711', 'font-weight', '900')
		$('input').blur(function() {
		var price = $('#price').val()	
		var shipping = $('#shipping').val()	
		var tax = $('#tax').val()	
		var total = (parseInt(price) + parseInt(shipping) + parseInt(tax));
			if (!isNaN(total)) {
			$('#poTotal').attr('value', total)
			} else {
			//alert('Oops Error! Please only numbers')
			}
	});	


$('#getResult').keyup(function(e){
    var val1 = $('#qty').val();
    var val2 = $('#unitPrice').val();
    var finalVal = parseFloat(val1)*parseFloat(val2);
    $('#lineTotal').html(finalVal);
});



	

	});
</script>

Open in new window

jQuery-help.png
0
t3chguy
Asked:
t3chguy
  • 3
1 Solution
 
psgindianaCommented:
Sounds like you want the "siblings", "children", and "each" commands.

$(".qty").change() (function() {
   this.siblings(".amount").val(this.val() * $("#UnitPrice").val());
}

$("table.distributionTable > tbody > tr").each(function() {
   $("#total").val() = $("#total").val() + (this.children(".qty") * $("#UnitPrice").val());
}

Open in new window

0
 
t3chguyAuthor Commented:
Thank you for the above script.  Unfortunately it doesn't seem to be doing anything when I key in values.
0
 
t3chguyAuthor Commented:
I'm a little bit closer now....

It adds up the Unit Price, Tax, and Shipping perfectly.

What I need to do now is figure out how to use that Unit Price and multiply whatever quantity I add in the quantity box, then that figure will go a few table cells over into the amount box, and then will update the box in which my sums appear.

	<form id="createDistribution" name="createDistribution" method="POST" enctype="multipart/form-data" action="">
		<input type="hidden" name="vendoracct" value = "<?=$vendorid?>">
		<div id="container" class="shadow">
			<div id="row">
				<div id="left">
					<strong>Description:</strong>
				</div>
				<div id="defaultdiv">
					<div id="right">
						<input type="text" class="fieldclasssm" name="linedescr[]" value = "<? if (!empty($_POST['custRef'])) { echo "value='".safeData($_POST['custRef'])."'"; }?>" size="113" />
					</div>
				</div>
			</div>
			<div id="row">
				<div id="left">
					<strong>Unit Price:</strong>
				</div>
				<div id="defaultdiv">
					<div id="right" class="total">
						<input type="text" class="fieldclasssm" name="sum" id="unitPrice"  size="10"/>
					</div>
				</div>
			</div>
			<div id="row">
				<div id="left">
					<strong>Tax:</strong>
				</div>
				<div id="defaultdiv">
					<div id="right" class="total">
						<input type="text" class="fieldclasssm" name="sum" id="tax" size="10"/>
					</div>
				</div>
			</div>
			<div id="row">
				<div id="left">
					<strong>Shipping:</strong>
				</div>
				<div id="defaultdiv">
					<div id="right" class="total">
						<input type="text" class="fieldclasssm" name="sum" id="shipping" size="10"/>
					</div>
				</div>
			</div>
			<div id="row">
				<div id="left">
					<strong>Distributions:</strong>
				</div>
				<div id="defaultdiv">
					<div id="right">
						<table border="0" width="800px" cellspacing="0" cellpadding="0" name="distributions" id = "distributions">
							<thead>
								<tr>
									<th class="colheader" width="65px">Qty</th>
									<th class="colheader" width="325px">Nominal Code</th>
									<th class="colheader" width="300px">Depot</th>
									<th class="colheader" width="100px">Amount</th>
									<th class="colheader" width="110px"><span class="boldblacklinks"><a href="#" id="add">[Add +]</a></span></th>
								</tr>
							</thead>
							<tbody class="lineBdy">
								<tr id="line_1" class="spacer">
									<td><input type="text" class="fieldclasssm" id="qty_item_1" name="distQty[]" size="5" /></td>
									<td><input type="text" class="nominal fieldclasssm" name="distNomCode[]" size="53" /></td>
									<td><input type="text" class="depot fieldclasssm" name="distDepot[]" size="50" /></td>
									<td><input type="text" class="fieldclasssm" id="distAmount[]" name="total_item" size="10" disabled />
									</td>
									<td>&nbsp;</td>
								</tr>
							</tbody>
						</table>
						<input type="hidden" id="items" name="items" value="1" /> 
						<input type="hidden" id="numRows" value= "<?=$numRows?>" />
						<br /><br />
					</div>
				</div>
			</div>
			<div id="row">
				<div id="left">
					<strong>PO Total:</strong>
				</div>
				<div id="defaultdiv">
					<div id="right" class="total">
						<input name="totalSum" class="fieldclasssm" id="totalSum" value="" size="6" readonly="readonly"  disabled type="text">
					</div>
				</div>
			</div>
			<div align="center"><br /><input type="submit" name="saveClose" class="btn" value = "Save & Finish Distribution"> <input type="submit" class="btn" name="saveCont" value="Save & Add New Item"><br /><br /></div>
		</div>
	</form>
	<br /><br /><br /><div align="center"><hr width="75%"></div><br /><br />	
		
	<?php
		
	//Summary Info
	$getItems = mysql_query("SELECT itemid, description, qty, amount, shipping, tax FROM pr_po_items WHERE poNumber = '".$poNum."'");

	if(mysql_num_rows($getItems) > 0)
		{ ?>
		
		<input type="hidden" name="vendoracct" value = "<?=$vendorid?>">
		<div id="container" class="shadow">
			<div id="row">
				<div id="left">
					<strong>Distributions:</strong>
				</div>
				<div id="defaultdiv">
					<div id="right">
						<span class="boldgreenlinks"><a href="lineItems.php" class="iframe">Create Item & Distributions</span></a>
					</div>
				</div>
			</div>
		</div>	
	<?	}
	
	else
		{
		echo '<div align="center"><span class="errormessagered"><strong>No items have been found for Purchase Order #'.$poNum.'.</span></div>';
		}
	break;
	}
?>


<link rel="stylesheet" type="text/css" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.9.2/themes/base/jquery-ui.css" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.9.2/jquery-ui.min.js"></script>
<script type="text/javascript" src="calculation.js"></script>
<script type="text/javascript">

$(function () 
	{
	/*Used for if Billing address changes, as of now, this will never change though.
	$("#usedefaultbill").click(function () {
        $("#newdivbill").hide();
     });
    $("#usealternatebill").click(function () {
        $("#newdivbill").show();
    });
	*/
	
	//Show extra fields if shipping location is not a warehouse.
	$("#usedefaultship").click(function () {
        $("#newdivship").hide();
     });
    $("#usealternateship").click(function () {
        $("#newdivship").show();
    });

	//Hide Customer Reference by default, show with condition.
	$("#poType").change(function()
		{
		$("#showcustref").hide();
			var chosenValue = $("#poType").val();
			if (chosenValue == "5" || chosenValue == "3" ) 
				{
				$("#showcustref").show();
				}  
		});

	//This is the autocomplete & autofill for shipping company search fields.
	$("#compname").autocomplete(
		{
		source: "autocomplete.php",
		minLength: 3,
		select: function(event, ui) 
			{
			event.preventDefault();
			$("#compid").val(ui.item.id);
			$("#compname").val(ui.item.label);
			$(':text[name=shipCompName]').val(ui.item.label);
			$(':text[name=shipAddress]').val(ui.item.address);
			$(':text[name=shipCity]').val(ui.item.town);
			$(':text[name=shipState]').val(ui.item.state);
			$(':text[name=shipZip]').val(ui.item.postcode);
			}
		});

	/*Not sure this is needed anymore.
	$("#compid").change( function () {
	  $("#submit").trigger('click');
	}); 
	*/

	//Add new table row & clone nominal
	$('#add').on('click', function(){
	   DistributionAddLine();
	});


	function DistributionAddLine(){
		 var lastID = $('tr[id*="line_"]').length,    
			 newTds = $('tr[id="line_' + lastID + '"] td').clone(),
			 newRow = document.createElement('tr');
	   
		// add new id and class to row, append cloned tds
		$(newRow)
			.attr('id', 'line_' + (lastID + 1 ))
			.attr('class', 'spacer')
			.append(newTds)
		;
		
		//empty out the fields, except the one you want to keep populated
		$(newRow).find('input').not(':eq(1)').val('');
		
		//add the new row to the table body
		$('tbody.lineBdy').append(newRow);
		
	}
		
	//Autocomplete nominal & depot fields on first row.
	$('.nominal').autocomplete({source:'suggestNominal.php', minLength:2});
	$('.depot').autocomplete({source:'suggestDepot.php', minLength:2});
	

$("input[name^=sum]").sum("keyup", "#totalSum");

	});

</script>
	<script type="text/javascript">
	var bIsFirebugReady = (!!window.console && !!window.console.log);

	$(document).ready(
		function (){
			// update the plug-in version
			$("#idPluginVersion").text($.Calculation.version);

/*			
			$.Calculation.setDefaults({
				onParseError: function(){
					this.css("backgroundColor", "#cc0000")
				}
				, onParseClear: function (){
					this.css("backgroundColor", "");
				}
			});
*/
			
			// bind the recalc function to the quantity fields
			$("input[name^=qty_item_]").bind("keyup", recalc);
			// run the calculation function now
			recalc();

			// automatically update the "#totalSum" field every time
			// the values are changes via the keyup event
			$("input[name^=sum]").sum("keyup", "#totalSum");
			
			// automatically update the "#totalAvg" field every time
			// the values are changes via the keyup event
			$("input[name^=avg]").avg({
				bind:"keyup"
				, selector: "#totalAvg"
				// if an invalid character is found, change the background color
				, onParseError: function(){
					this.css("backgroundColor", "#cc0000")
				}
				// if the error has been cleared, reset the bgcolor
				, onParseClear: function (){
					this.css("backgroundColor", "");
				}
			});

function recalc(){
		$("[id^=total_item]").calc(
			// the equation to use for the calculation
			"qty * price",
			// define the variables used in the equation, these can be a jQuery object
			{
				qty: $("input[name^=qty_item_]"),
				price: $("[id^=price_item_]")
			},
			// define the formatting callback, the results of the calculation are passed to this function
			function (s){
				// return the number as a dollar amount
				return "$" + s.toFixed(2);
			},
			// define the finish callback, this runs after the calculation has been complete
			function ($this){
				// sum the total of the $("[id^=total_item]") selector
				var sum = $this.sum();
				
				$("#grandTotal").text(
					// round the results to 2 digits
					"$" + sum.toFixed(2)
				);
			}
		);
	}
	</script>

Open in new window

1
 
t3chguyAuthor Commented:
I figured this out on my own.
0

Featured Post

Receive 1:1 tech help

Solve your biggest tech problems alongside global tech experts with 1:1 help.

  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now