troubleshooting Question

jquery order form with dynamic rows

Avatar of iceman19330
iceman19330 asked on
AJAXjQuery
8 Comments1 Solution1557 ViewsLast Modified:
I am at the point of frustration with this form.  I get to a point and find a setback, get around the setback and there is another setback.  Before I go and do something stupid I was hoping someone could point out what the heck I am messing up.

I have attached the full js and the html porttion of the form.  

What works is the first line adds up everything fine, well I havent worked on the shipping or order total part, but that not what I am after.

What does not work is when you clone the row nothing adds up anymore, not on the same line and not down below.  What also needs to happen is then when I delete the row the totals get recalculated.

If I had hair I would be pulling it out.  Please help.
<script type="text/javascript">
var newRowNum = 0;
$(document).ready(function(){

	//$('.total_change').bind('blur',function() {
		//var price = $('#order_item_price').val()	
		//var quantity = $('#order_qty').val()	
		//var total = price * quantity;
		//if (!isNaN(total)) {					
			//$('#order_item_total').attr('value', total.toFixed(2))
		//} else {
			//alert('Ops Error! Please only numbers')
		//}
	//});	
		
	
    $('#add-order-row').click(function(){
		newRowNum += 1;
		var addRow = $(this).parent().parent();
        var masterRow = addRow.next();
		var newRow = masterRow.clone(false);
            
        // Change the ids for the new row
        //$(newRow).attr({
			//'id'    : 'order-row-' + newRowNum,
			//'name'  : 'order-row-' + newRowNum
        //}).find(':input, button, select').each(function(){
		//$(this).attr({
			//'id'    : $(this).attr('id') + "_" + newRowNum,
			//'name'  : $(this).attr('name') + "_" + newRowNum,
			//'class'  : $(this).attr('class') + "_" + newRowNum
		//});
	//}); 
   	// Append new row to DOM                
	masterRow.after(newRow);
	//$('#order_item_product_' + newRowNum).change(function () {
		//var id = $('#order_item_product_' + newRowNum).val();
		//$('#order_item_price_' + newRowNum).val($('#order_item_product').data(id).price);
	//}).change();

	//$('.total_change_' + newRowNum).change(function() {
		//var price = $('#order_item_price_' + newRowNum).val()	
		//var quantity = $('#order_qty_' + newRowNum).val()	
		//var total = price * quantity;
		//if (!isNaN(total)) {					
			//$('#order_item_total_' + newRowNum).attr('value', total.toFixed(2))
		//} else {
			//alert('Ops Error! Please only numbers')
		//}
	//}).change();	
      
	// Add the remove function to the new row
	$('button#order_item_delete_' + newRowNum).click(function(){
		$(this).parent().parent().remove();
		return false;                           
	});
	// prevent the default click
	return false;
	});
});


function moneyFormat(input) {
	   var dollars = Math.floor(input);
	   var tmp = new String(input);

	   for ( var decimalAt = 0; decimalAt < tmp.length; decimalAt++ ) {
	      if ( tmp.charAt(decimalAt)=="." )
	         break;
	   }

	   var cents  = "" + Math.round(input * 100);
	   cents = cents.substring(cents.length-2, cents.length)
	           dollars += ((tmp.charAt(decimalAt+2)=="9")&&(cents=="00"))? 1 : 0;

	   if ( cents == "0" )
	      cents = "00";

	   return(dollars + "." + cents);
	}

function IsNumeric(sText)

{
var ValidChars = "0123456789.";
var IsNumber=true;
var Char;


for (i = 0; i < sText.length && IsNumber == true; i++) 
   { 
   Char = sText.charAt(i); 
   if (ValidChars.indexOf(Char) == -1) 
      {
      IsNumber = false;
      }
   }
return IsNumber;

};

function calcProdSubTotal() {
 
 var prodSubTotal = 0;
 $("#order_item_total").each(function(){
     var valString = $(this).val() || 0;
     prodSubTotal += parseFloat(valString);
 });
 
 $("#order_product_total").val(moneyFormat(prodSubTotal));

};

function calcTotalQty() {
 var totalQty = 0;
 $("#order_qty").each(function() {
     var thisValue = $(this).val();
     if ( (IsNumeric(thisValue)) &&  (thisValue != '') ) {
         totalQty += parseInt(totalQty);    
     };
 });
 $("#total_order_qty").val(totalQty);
};

function calcShippingTotal() {
	
	// will have to change to work UPS and USPS options in.
	
 var totalQty = $("#total_order_qty").val() || 0;
 var weightPerItem = 25;
 var shippingMath = weightPerItem/100;
 //var shippingRate = $("#shipping-rate").text() || 0;
 var shippingRate = '1.25';
 var shippingWeight = parseInt(totalQty) * parseInt(weightPerItem);
 
 var shippingTotal = parseInt(shippingWeight) * parseInt(shippingRate);
 
 $("#order_shipping").val(moneyFormat(shippingTotal));

};

function calcTaxTotal() {
	
	// right now tax is only from NJ can pull tax rate from DB later.
	
 var totalProd = $("#order_product_total").val() || 0;
 //alert("total prod" + totalProd);
 var taxRate = 7;
 var taxMath = taxRate/100;
 var taxTotal = parseFloat(totalProd) * parseFloat(taxMath);
 
 $("#order_tax").val(moneyFormat(taxTotal));

};

function calcOrderTotal() {

 var orderTotal = 0;

 var productSubtotal = $("#order_product_total").val() || 0;
 var productTax = $("#order_tax").val() || 0;
 var shippingSubtotal = $("#order_shipping").val() || 0;
     
 var orderTotal = parseInt(productSubtotal) + parseFloat(productTax) + parseFloat(shippingSubtotal);
 
 $("#order-total").val(moneyFormat(orderTotal));
     
};

$(document).ready(function(){

	$('.total_change').bind('blur',function() {
 
     var $this = $(this);
     
     var price = $('#order_item_price').val()	
		var quantity = $('#order_qty').val()
     
     //var numPallets = $this.val();
     //var multiplier = $this
                         //.parent().parent()
                         //.find("td.price-per-pallet span")
                         //.text();
     
     if ( (IsNumeric(price)) && (price != '') && (IsNumeric(quantity)) && (quantity != '') ) {
         
         var rowTotal = parseInt(quantity) * parseFloat(price);
         $('#order_item_total').val(moneyFormat(rowTotal));                    
         
     } else {
     
         $this.css("background-color", "#ffdcdc"); 
                     
     };
     
     calcProdSubTotal();
     calcTotalQty();
     
     calcTaxTotal();
     calcShippingTotal();
     calcOrderTotal();
 
 });

});


$(document).ready(function(){
	$.extend({
	getUrlVars: function(){
		var vars = [], hash;
		var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
		for(var i = 0; i < hashes.length; i++) {
			hash = hashes[i].split('=');
			vars.push(hash[0]);
			vars[hash[0]] = hash[1];
		}
		return vars;
	},
	getUrlVar: function(name){
		return $.getUrlVars()[name];
	}
	});
	$.ajax({
		type: "GET",
		url: "query.php",
		dataType: "xml",
		data: {'type' : 'status'},
		success: function(xml) {
			var select = $('#order_item_status');
			$(xml).find('entry').each(function(){
				var orders_status_id = $(this).find('orders_status_id').text();
				var orders_status_name = $(this).find('orders_status_name').text();
				select.append("<option value='"+ orders_status_id +"'>"+orders_status_name+"</option>");
			});
		}
	});
	$.ajax({
		type: "GET",
		url: "query.php",
		dataType: "xml",
		data: {'type' : 'products'},
		success: function(xml) {
			var select = $('#order_item_product');
			$(xml).find('entry').each(function(){
				var products_id = $(this).find('products_id').text();
				var products_name = $(this).find('products_name').text();
				var products_price = $(this).find('products_price').text();
				select.append("<option value='"+ products_id +"'>"+products_name+"</option>");
				//$("input[name='order_item_price']").val(products_price);
				//$('#order_item_product').data(products_id, { name: products_name, price: products_price });
				//$('#order_item_product').change(function () {
					//var id = $('#order_item_product').val();
					//$('#order_item_price').val($('#order_item_product').data(id).price);      
			    //}).change();
			});
		}
	});
	var id = $.getUrlVar('id');
	alert("my id is " + id);
	$.ajax({
		type: "GET",
		url: "query.php",
		dataType: "xml",
		data: {'id' : id, 'type' : 'address'},
		success: function(xml) {
			var select = $('#customer_billing_id');
			var select1 = $('#customer_shipping_id');
			var telephone_field = $('#customers_telephone');
			var email_address_field = $('#customers_email_address');
			$(xml).find('entry').each(function(){
				var address_book_id = $(this).find('address_book_id').text();
				var customers_fullname = $(this).find('customers_fullname').text();
				var customer_street_address = $(this).find('customer_street_address').text();
				var customer_city = $(this).find('customer_city').text();
				var customer_state = $(this).find('customer_state').text();
				var customer_postal_code = $(this).find('customer_postal_code').text();
				var customer_country = $(this).find('customer_country').text();
				var customers_email_address = $(this).find('customers_email_address').text();
				var customers_telephone = $(this).find('customers_telephone').text();
				select.append("<option value='"+ address_book_id +"'>"+customers_fullname+" "+customer_street_address+" "+customer_city+", "+customer_postal_code+""+customer_country+"</option>");
				select1.append("<option value='"+ address_book_id +"'>"+customers_fullname+" "+customer_street_address+" "+customer_city+", "+customer_postal_code+""+customer_country+"</option>");
				$("input[name='customers_telephone']").val(customers_telephone);
				$("input[name='customers_email_address']").val(customers_email_address);
			});
		}
	});
});

</script>


html --------------

<fieldset>
		<legend>Product Order Sheet</legend>
		<input type="hidden" id="total_order_qty" name="total_order_qty" value="">
		<dl>
			<p style="line-height: 5px;"><button type="button" name="add-order-row" id="add-order-row">Add Row</button></p>
		</dl>
        <dl id="order-row" name="order-row">
        	<dd style="line-height: 5px; text-align: right;">Qty:<input type="text" name="order_qty" id="order_qty" class="total_change" size="6" maxlength="6" />&nbsp;&nbsp;&nbsp;Product:<select size="1" name="order_item_product" id="order_item_product" class="total_change"></select>&nbsp;&nbsp;&nbsp;Price:<input type="text" name="order_item_price" id="order_item_price" class="total_change" size="6" maxlength="20" />&nbsp;&nbsp;&nbsp;Total:<input type="text" name="order_item_total" id="order_item_total" class="total_change" size="6" maxlength="20" />&nbsp;&nbsp;&nbsp;<button type="button" name="order_item_delete" id="order_item_delete" class="total_change">Delete</button></dd>
		</dl>
		<dl>
			<dd style="line-height: 5px; text-align: right; border-top: 2px solid black;">&nbsp;&nbsp;&nbsp;</dd>
		</dl>
		<dl>
			<dd style="line-height: 5px; text-align: right;">Product Total:&nbsp;&nbsp;&nbsp;<input type="text" name="order_product_total" id="order_product_total" size="6" maxlength="10" value="" /></dd>
		</dl>
		<dl>
			<dd style="line-height: 5px; text-align: right;">Tax:&nbsp;&nbsp;&nbsp;<input type="text" name="order_tax" id="order_tax" size="6" maxlength="10" /></dd>
		</dl>
		<dl>
			<dd style="line-height: 5px; text-align: right;">Shipping:&nbsp;&nbsp;&nbsp;<input type="text" name="order_shipping" id="order_shipping" size="6" maxlength="10" /></dd>
		</dl>
		<dl>
			<dd style="line-height: 5px; text-align: right;">Order Total:&nbsp;&nbsp;&nbsp;<input type="text" name="order_total" id="order_total" size="6" maxlength="10" value="$0.00" /></dd>
		</dl>
	</fieldset>
Join the community to see this answer!
Join our exclusive community to see this answer & millions of others.
Unlock 1 Answer and 8 Comments.
Join the Community
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 8 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros