/    Sign up×
Community /Pin to ProfileBookmark

Javascript sums for 2 different sub total fields help

Hello, I have a form that has item 1 – item 1’s cost is determined by the length and width (square feet) and by the material price. This generates totalcost (for item 1)

Same thing happens for item 2.. This generates totalcost2 (for item2)

Now I need to create a function that will grab the content/values of these totals and display a TOTAL VALUE.. I would think this would be simple but I can’t seem to figure it out.

Again totalcost + totalcost2 = grandTotal

Any help would be appreciated – function code and html for webpage.
Thx

to post a comment
JavaScript

43 Comments(s)

Copy linkTweet thisAlerts:
@Sup3rkirbyApr 22.2014 — Do you have any code at all to base this off of? I'd like to see what you have so I know exactly what you need added.

In your original post your equation would appear to be correct for the most part, thus I don't think I understand what you are needing in order to get your page working as desired. Is it that you aren't getting the right value? If that's the case you merely need to make sure you add the values as numbers (and not strings).
[CODE]
var grandTotal = Number(totalcost) + Number(totalcost2);
var grandTotal = (totalcost * 1) + (totalcost2 * 1);
[/CODE]

There's two simple ways to force the variables to numbers before adding (to ensure it doesn't concat them as strings).

Or is your problem just that you need a function to return the sum of these values? (though I feel a function is unecessary, you could just combine the totals elsewhere).
[CODE]
function _GetTotal($a, $b) {
return ($a * 1) + ($b * 1);
}

var totalcost = 123;
var totalcost2 = 456;
var grandTotal = _GetTotal(totalcost, totalcost2);
[/CODE]


Again, I'm not really sure what you are asking in context. You already seem to have a working system for most of this, just not the grand total, however it's hard to tell you what to do in relation to your code, since none of that is here for reference. So if you need the grand total displayed on the page for example, we here at the forum have no idea where to display it on the page without seeing code. Or if you already have something set up to do this but it just isn't working right, we here at the forum cannot fix the code you have without seeing it.
Copy linkTweet thisAlerts:
@JMRKERApr 22.2014 — "Given billions of tries, could a spilled bottle of ink ever fall into the words of Shakespeare?"[/QUOTE]

Stupid side question: "into" or "onto"?

My stupid guess answer: "no" or "yes". ?

Additional information request: Are we near any gravity? ?
Copy linkTweet thisAlerts:
@sherryrauthorApr 23.2014 — Hi, thanks for the quick reply. Below is the code.

I was trying to add the grandtotal code to the file calculator.js with these functions which basically add calculate the square footage and the price of each item.

function Calculate(frm) {

var order_total, length, width, i;

order_total = 0;


length = parseFloat(frm.length.value);
width = parseFloat(frm.width.value);

if (length > 0 && width > 0) {
order_total = length * width;
for (i = 0; i < frm.tooling.length; i++) {
if (frm.tooling[i].value === "withouttooling" && frm.tooling[i].checked === true) {
order_total = order_total * ".30";
}
if (frm.tooling[i].value === "withtooling" && frm.tooling[i].checked === true) {
order_total = order_total * ".40";
}
}
//order_total = order_total * .35
order_total = order_total + 25;
}
else {
order_total = 0;
}

// Run through all the form fields
//for (var i=0; i < frm.elements.length; ++i) {

// Get the current field
//form_field = frm.elements[i]

// Get the field's name
//form_name = form_field.name

// Is it a "product" field?
//if (form_name.substring(0,4) == "PROD") {

// If so, extract the price from the name
//item_price = parseFloat(form_name.substring(form_name.lastIndexOf("_") + 1))

// Get the quantity
//item_quantity = parseInt(form_field.value)

// Update the order total
//if (item_quantity >= 0) {
//order_total += item_quantity * item_price
//}
//}
//}

// Display the total rounded to two decimal places
frm.totalcost.value = '$ ' + round_decimals(order_total, 2);

}

function round_decimals(original_number, decimals) {

var result1 = original_number * Math.pow(10, decimals);

var result2 = Math.round(result1);

var result3 = result2 / Math.pow(10, decimals);

return pad_with_zeros(result3, decimals);

}

function pad_with_zeros(rounded_value, decimal_places) {

// Convert the number to a string
var value_string = rounded_value.toString();

// Locate the decimal point
var decimal_location = value_string.indexOf(".");

// Is there a decimal point?
if (decimal_location == -1) {

// If no, then all decimal places will be padded with 0s
decimal_part_length = 0;

// If decimal_places is greater than zero, tack on a decimal point
value_string += decimal_places > 0 ? "." : "";
}
else {

// If yes, then only the extra decimal places will be padded with 0s
decimal_part_length = value_string.length - decimal_location - 1;
}

// Calculate the number of decimal places that need to be padded with 0s
var pad_total = decimal_places - decimal_part_length;

if (pad_total > 0) {

// Pad the string with 0s
for (var counter = 1; counter <= pad_total; counter++) {
value_string += "0";
}
}
return value_string;

}


function Calculateitem2(frm) {

var order_total2, length2, width2, i;

order_total2 = 0;


length = parseFloat(frm.length2.value);
width = parseFloat(frm.width2.value);

if (length > 0 && width > 0) {
order_total2 = length * width;
for (i = 0; i < frm.tooling2.length; i++) {
if (frm.tooling2[i].value === "withouttooling" && frm.tooling2[i].checked === true) {
order_total2 = order_total2 * ".30";
}
if (frm.tooling2[i].value === "withtooling" && frm.tooling2[i].checked === true) {
order_total2 = order_total2 * ".40";
}
}
//order_total2 = order_total2 * .35
order_total2 = order_total2 + 25;
}
else {
order_total2 = 0;
}

// Run through all the form fields
//for (var i=0; i < frm.elements.length; ++i) {

// Get the current field
//form_field = frm.elements[i]

// Get the field's name
//form_name = form_field.name

// Is it a "product" field?
//if (form_name.substring(0,4) == "PROD") {

// If so, extract the price from the name
//item_price = parseFloat(form_name.substring(form_name.lastIndexOf("_") + 1))

// Get the quantity
//item_quantity = parseInt(form_field.value)

// Update the order total
//if (item_quantity >= 0) {
//order_total2 += item_quantity * item_price
//}
//}
//}

// Display the total rounded to two decimal places
frm.totalcost2.value = '$ ' + round_decimals(order_total2, 2);

}

function round_decimals(original_number, decimals) {

var result1 = original_number * Math.pow(10, decimals);

var result2 = Math.round(result1);

var result3 = result2 / Math.pow(10, decimals);

return pad_with_zeros(result3, decimals);

}

function pad_with_zeros(rounded_value, decimal_places) {

// Convert the number to a string
var value_string = rounded_value.toString();

// Locate the decimal point
var decimal_location = value_string.indexOf(".");

// Is there a decimal point?
if (decimal_location == -1) {

// If no, then all decimal places will be padded with 0s
decimal_part_length = 0;

// If decimal_places is greater than zero, tack on a decimal point
value_string += decimal_places > 0 ? "." : "";
}
else {

// If yes, then only the extra decimal places will be padded with 0s
decimal_part_length = value_string.length - decimal_location - 1;
}

// Calculate the number of decimal places that need to be padded with 0s
var pad_total = decimal_places - decimal_part_length;

if (pad_total > 0) {

// Pad the string with 0s
for (var counter = 1; counter <= pad_total; counter++) {
value_string += "0";
}
}
return value_string;

}
Copy linkTweet thisAlerts:
@sherryrauthorApr 23.2014 — html form code

<form class="order-form" method="post" action="emaileverything.php">

<ul class="colleft">

<li>

<p>Company<br/><br />

<input name="company"></p>

<p>Contact<br/><br />

<input name="contact"></p>

<p>Address<br/><br />

<input name="address"></p>

<p>City<br/><br />

<input name="city"></p>

<p>State/Province<br/></p>

<select size="1" name="state">

<option selected="selected" value=""></option>

<p><optgroup label="United States"></p>

<option value="AL">Alabama</option>

<p></optgroup><br />

<optgroup label="Canadian Provinces"></p>

<option value="AB">Alberta</option>

<p></optgroup><br />

</select>

</p>

<p>Zip/Postal Code<br/><br />

<input name="Zip"></p>

<p>Phone<br/><br />

<input name="phone"></p>

<p>Email address<br/><br />

<input name="email"></p>

<p>Fax<br/><br />

<input name="fax"></p>

<p>Shipping address<br />

<input class="checkbox" name="shipping" type="checkbox"><small>(Same)</small><br/><br />

<textarea style="WIDTH: 202px; HEIGHT: 50px" rows="1" name="shippingaddress"></textarea><br/><br />

<br/><br />

Comments<br/><br />

<textarea style="WIDTH: 202px; HEIGHT: 44px" rows="1" cols="50" name="comments"></textarea>&nbsp;<br/>

</p>

</li>

<p><strong>Item 1</strong><BR>

<li><input class="checkbox" name="colorcardonly" type="checkbox"><strong>Order color card only</strong></p>

<p>Dimensions of leather to the nearest .25 ”<br/></p>

<p>Width<br />

<input class="short" onchange="Calculate(this.form)" name="width"><small>(in)</small><br/><br />

Length<br />

<input class="short" onchange="Calculate(this.form)" name="length"><small>(in)</small></p>

<p><input class="checkbox" onclick="Calculate(this.form)" value="withouttooling" checked="checked" name="tooling" type="radio"> No Tooling Design<br/><br />

<input class="checkbox" onclick="Calculate(this.form)" value="withtooling" name="tooling" type="radio"> With tooling design<br/><br />

<small style="FONT: 10px Arial,Helvetica,sans-serif">(All tooling Gold unless otherwise specified)</small></p>

<p>Tooling design inset<br/><br />

Choose<br />

<input class="checkbox" value="1/2 inch" name="inset" type="radio"> 1/2”<br />

<input class="checkbox" value="3/4 inch" name="inset" type="radio"> 3/4”<br />

<input class="checkbox" value="1 inch" name="inset" type="radio"> 1”</p>

<p>Plus $25.00 shipping</p>

<hr/><BR></p>

<p style="PADDING-BOTTOM: 0pt"><strong>Total Cost</strong><input class="short" onfocus="this.form.elements[0].focus()" name="totalcost" id="totalcost" / onChange="updatesum()" /></p>

<p><BR><BR><strong>Item 2</strong><br />

<BR><br />

<input class="checkbox" type="checkbox" name="colorcardonly2" /><strong>Order color card only</strong></p>

<p>Dimensions of leather to the nearest .25 ”<br />

<BR><br />

<BR> Colour</p>

<p>&nbsp;</p>

<select name="item2colour" size="1">

<option value="Blk">Black</option>

<option value="Rust">Rust</option>

</select>

<p>&nbsp;</p>

<p><BR></p>

<p> <BR>Tooling Style</p>

<p>&nbsp;</p>

<select name="item2tooling2" size="1">

<option value="patter1">Pattern 1</option>

<option value="patter2">Pattern 2</option>

</select>

<p>&nbsp;</p>

<p><BR><br />

Width<br />

<input class="short" type="text" name="width2" onchange="Calculateitem2(this.form)" /><small>(in)</small><br />

<BR><br />

Length<br />

<input class="short" type="text" name="length2" onchange="Calculateitem2(this.form)" /><small>(in)</small></p>

<p><input class="checkbox" onclick="Calculateitem2(this.form)" type="radio" name="tooling2" value="withouttooling" checked="checked" > No Tooling Design</p>

<p> <input class="checkbox" onclick="Calculateitem2(this.form)" type="radio" name="tooling2" value="withtooling" /> With tooling design</p>

<p><BR> <small style="font: 10px Arial,Helvetica,sans-serif;">(All tooling Gold unless otherwise specified)</small><br />

<BR><br />

Tooling design inset</p>

<p> Choose<br />

<input class="checkbox" type="radio" name="inset" value="1/2 inch" /> 1/2”<br />

<input class="checkbox" type="radio" name="inset" value="3/4 inch" /> 3/4”<br />

<input class="checkbox" type="radio" name="inset" value="1 inch" /> 1”</p>

<p>Plus $25.00 shipping</p>

<hr />

<BR></p>

<p><strong>Total Cost</strong><input class="short" type="text" name="totalcost2" onfocus="this.form.elements[0].focus()" /onChange="updatesum()" /><BR></p>

</li></form>

working example with added attempts at "grandTotal" - http://www.webcrawldesigns.com/dct/order-form-test/
Copy linkTweet thisAlerts:
@Sup3rkirbyApr 23.2014 — First things first, I have to admit, your HTML is pretty jumbled. It certainly wouldn't pass a validator as it's missing some closing tags, and other tags don't follow the 'order of operations' (ie. closing inner-most tags before closing outer-most tags). I won't really address all of the HTML issues though as that's not what this topic is about and it'd be quite a task to rebuild/reformat all of the code.

Now, for the javascript. A few quick notes: you duplicated your round_decimals() and pad_with_zeroes() functions. I also felt those two functions were awfully... bulky. I included a minified function for formatting numbers. I also removed some of the commented code.

The first thing to do would be add the HTML element to hold your grand total. Something like this will suffice:
[code=html]
Grand Total: <span id="grandTotal"></span>
[/code]

I feel like it makes more sense to be putting these values in regular text elements rather than [B]<input>[/B] elements since they are not editable values. Of course, I guess this assumes you aren't actually wanting to submit the value with the form. But in that case I feel it's a little silly to pass the total values via form since it's possible to easily modify those values and thus your submitted data would be tainted and wrong. You should be processing order totals that actually get used on the server's side to avoid potential issues.

Now for the script, below is essentially all you need. I do feel you could optimize your calculate functions (for instance, you could set up just 1 that takes in 3 parameters, the length field, width field and the output element/field for the total), but it's not a huge deal, it would just be cleaner and more optimized code.
[CODE]
if(typeof(_N) != "function") function _N($n, $d) { return ($d) ? Number($n).toFixed($d).toString().replace(/B(?=(d{3})+(?!d))/g, ",") : $n.toString().replace(/B(?=(d{3})+(?!d))/g, ","); }

function Calculate(frm) {
var order_total, length, width, i;
order_total = 0;

length = parseFloat(frm.length.value);
width = parseFloat(frm.width.value);

if(length > 0 && width > 0) {
order_total = length * width;
for(i = 0; i < frm.tooling.length; i++) {
if (frm.tooling[i].value === "withouttooling" && frm.tooling[i].checked === true) order_total = order_total * ".30";
if (frm.tooling[i].value === "withtooling" && frm.tooling[i].checked === true) order_total = order_total * ".40";
}
//order_total = order_total * .35
order_total = order_total + 25;
} else {
order_total = 0;
}

// Display the total rounded to two decimal places
//frm.totalcost.value = '$ ' + round_decimals(order_total, 2);
frm.totalcost.value = '$' + _N(order_total, 2);
_CalculateTotal(frm);
}


function Calculateitem2(frm) {
var order_total, length, width, i;
order_total = 0;

length = parseFloat(frm.length2.value);
width = parseFloat(frm.width2.value);

if(length > 0 && width > 0) {
order_total = length * width;
for(i = 0; i < frm.tooling2.length; i++) {
if(frm.tooling2[i].value === "withouttooling" && frm.tooling2[i].checked === true) order_total = order_total * ".30";
if(frm.tooling2[i].value === "withtooling" && frm.tooling2[i].checked === true) order_total = order_total * ".40";
}
//order_total2 = order_total2 * .35
order_total = order_total + 25;
} else {
order_total = 0;
}

// Display the total rounded to two decimal places
//frm.totalcost2.value = '$ ' + round_decimals(order_total, 2);
frm.totalcost2.value = '$' + _N(order_total, 2);
_CalculateTotal(frm);
}

function _CalculateTotal($f) {
var $total1 = parseFloat($f.totalcost.value.replace(/[^0-9.]/g, ""));
var $total2 = parseFloat($f.totalcost2.value.replace(/[^0-9.]/g, ""));
console.log($total1, $total2);
document.getElementById("grandTotal").innerHTML = (!isNaN($total1) && !isNaN($total2)) ? "$" + _N($total1 + $total2, 2) : "";
}

function round_decimals(original_number, decimals) {
var result1 = original_number * Math.pow(10, decimals);
var result2 = Math.round(result1);
var result3 = result2 / Math.pow(10, decimals);
return pad_with_zeros(result3, decimals);
}

function pad_with_zeros(rounded_value, decimal_places) {
// Convert the number to a string
var value_string = rounded_value.toString();

// Locate the decimal point
var decimal_location = value_string.indexOf(".");

// Is there a decimal point?
if(decimal_location == -1) {
// If no, then all decimal places will be padded with 0s
decimal_part_length = 0;

// If decimal_places is greater than zero, tack on a decimal point
value_string += decimal_places > 0 ? "." : "";
} else {
// If yes, then only the extra decimal places will be padded with 0s
decimal_part_length = value_string.length - decimal_location - 1;
}

// Calculate the number of decimal places that need to be padded with 0s
var pad_total = decimal_places - decimal_part_length;

if(pad_total > 0) {
// Pad the string with 0s
for(var counter = 1; counter <= pad_total; counter++) {
value_string += "0";
}
}
return value_string;
}
[/CODE]


Each time a total is calculated, the grand total also gets calculated. This isn't the most optimal way to do it, but again your calculate functions could be optimized and merged into one, and could be built to actually check to make sure a total exist for both items before calculating the grand total. But for now, this is a working version that does the job just fine. It will strip any 'bad' characters to get the totals as numbers, then of course adds them and places them in the [B]<span>[/B] element I gave you earlier in this post.
Copy linkTweet thisAlerts:
@sherryrauthorApr 23.2014 — Thank you so much for this. I just didn't copy all the html.. It is complete and coded right in my form ?

A question: If I add a drop down that can show up to 4 items will this code calculate totalcost3 totalcost4 etc... if I modify the function Calculateitem2(frm) { code by changing all the 2's to 3's etc?
Copy linkTweet thisAlerts:
@sherryrauthorApr 23.2014 — Also when I receive the form results via email

Grand Total:<span id="grandTotal"> doesn't have a "form" label. Can I add this to the span so that the total amount is visible in the email?
Copy linkTweet thisAlerts:
@Sup3rkirbyApr 23.2014 — Again, I think you'd be much better off combining your calculate functions into one. Having 4 separate functions to calculate 4 items is a bad practice, especially if these items all use the same equation/algorithm for their calculation. You end up with a bunch of repeated code (and only 1 or 2 things changing per function).

If you are wanting to dynamically change the number of items being calculated, it would be even more beneficial to change how things are set up. Bascially, everything right now is static. Each calculation is coded for one specific thing/item and thus the grand total is coded for the 2 specific items you have right now. I don't know if you have any sort of deadlines or schedules to adhere to with this but I can certainly take a look later today and a unified calculate and grand total function that would calculate any number of items.

And as for the labeling issue of the grand total, as I don't know what the content of the email looks like I can't really tell you what you should or shouldn't do to get a proper label showing up. If the grand total itself is showing up then I suppose you could always just modify my [B]_CalculateTotal()[/B] function to write "Grand Total: " in the [B]<span>[/B] innerHTML as well (and just remove the text label from the page. But by default have this string in the [B]<span>[/B] so the area is not blank to begin with).

[code=html]
<span id="grandTotal">Grand Total: </span>
[/code]

[CODE]
// This goes inside of the _CalculateTotal() function
// Replacing the last line of the function
document.getElementById("grandTotal").innerHTML = (!isNaN($total1) && !isNaN($total2)) ? "Grand Total: $" + _N($total1 + $total2, 2) : "Grand Total: ";
[/CODE]
Copy linkTweet thisAlerts:
@sherryrauthorApr 23.2014 — Hello, I used the code you posted above but would be OPEN and THANKFUL FOR A MORE EFFECTIVE APPROACH.

I think the shipping cost of $25 should only be applied to item 1 unless my requirements change.

If it is easy the code could show the option to add more items if a button is pressed. In most cases someone will only order 1 item but need the ability to add more.

As for the grandtotal coming through in my php email script.

Example of what I mean here is I have input for customer to fill in company name (html form)

<input name="company">

in my php form calls on the field name

$company = $_POST['company']; and the value will come through in the received email.

maybe the grandTotal will work the same, I will test it out. (from id)
Copy linkTweet thisAlerts:
@sherryrauthorApr 23.2014 — or I guess it would be more like this in php script

$email_message .= "Company: ".clean_string($company)."n";
Copy linkTweet thisAlerts:
@sherryrauthorApr 23.2014 — One more thing.. sorry for all the posts.. I noticed that if only 1 product is entered the grandTotal doesn't calculate until item 2 is identified. There might not be an item 2 so it needs to calculate no matter how many items.
Copy linkTweet thisAlerts:
@Sup3rkirbyApr 23.2014 — As far as the grand total not calculating until a second item is entered, this would mainly be because there is no default value for these items. Thus no total (an invalid total actually) and so the function can't display the total. If the length and width fields had a default value of "0" the grand total should be calculated regardless of how many items were entered.

But in all fairness, it's more the overall method for all calculations that needs to be adjusted for a proper result. Having one function that dynamically calculates a total for any item will resolve that issue (and others).

As for getting the grand total in your email, because you are checking [B]$_POST[/B] variables you will never see the grand total. [B]$_POST[/B] variables are set from form input values. Thus the only way to see values in [B]$_POST[/B] (AJAX aside) is having the value in an [B]<input>[/B] with a valid name property set (id is not used in $_POST).

I do feel I need to refer back to something I mentioned earlier when I mentioned putting the grand total in a [B]<span>[/B] and not an [B]<input>[/B]. It's a bad idea and practice to pass total values like your grand total via a form <input> when you are already passing all of the values necessary to calculate the total in PHP. Especially if you are dealing with an order system that deals with real live orders (and money), you shouldn't be using Javascript, a client-side language, to handle the official order totaling for your records. I'm not saying it's something that could often be a problem but it's an extremely simple task to edit the input values and submit the form. For instance I could enter my typical order information then press the magical F12 button (or right-click and 'Inspect Element') and then edit the value of the grand total. When I submit you could get a grand total of $0.01 which would be absolutely incorrect. You'd receive the email with the invalid info and if the order info is sent anywhere else (a database for instance) the info would be incorrect there as well. Sure, you could just look at the other order details and actually calculate the real grand total yourself, but why put yourself through all of the extra trouble? You should really only be passing the base information to PHP and then actually calculate the total in PHP before sending an email and saving the order. And don't get me wrong, you should still be calculating this on the front-end with Javascript to display the value to the user, but that value shouldn't be your 'final' total that you immediately save and send off because it's less likely to be correct all of the time than having the server (PHP) do the calculations instead.

That's just one case scenario as well. Overall you could run into other issues with values not always being passed correctly, javascript errors, disabled javascript, etc. And without PHP there to do the actual calculations you will be getting invalid orders and totals.
Copy linkTweet thisAlerts:
@sherryrauthorApr 23.2014 — Ok.. if you could come up with a function that would calculate the totals regardless of what is selected that would be great - this would resolve the number of items ordered and always show a total.. or suggest another method.

As for the post method.. I have taken an existing form that has a post method .. and customizing based on requirements. I would rather use a wordpress plugin but I need the square feet measured and values for the tooling as well as the image mouseovers as seen here - http://www.webcrawldesigns.com/dct/order-form-test/
Copy linkTweet thisAlerts:
@Sup3rkirbyApr 24.2014 — Below I have what should be a unified function that will calculate the total of any particular item, as well as a slightly updated grand total function.

I do want to note that this is sort of a 'hack job', which is something I hate to do, but if I'm being honest, a more proper solution would involve numerous changes to the rest of your HTML, which is something I wasn't looking to get into at the moment.
[CODE]
if(typeof(_N) != "function") function _N($n, $d) { return ($d) ? Number($n).toFixed($d).toString().replace(/B(?=(d{3})+(?!d))/g, ",") : $n.toString().replace(/B(?=(d{3})+(?!d))/g, ","); }

$itemCount = 2;
$lFields = ["length", "length2", "length3", "length4"];
$wFields = ["width", "width2", "width3", "width4"];
$tFields = ["totalcost", "totalcost2", "totalcost3", "totalcost4"];

function Calculate($a) {
var order_total, length, width, i;
order_total = 0;

length = parseFloat(document.forms[1][$lFiends[$a]].value);
width = parseFloat(document.forms[1][$wFiends[$a]].width.value);

if(length > 0 && width > 0) {
order_total = length * width;
for(i = 0; i < document.forms[1]["tooling"].length; i++) {
if (document.forms[1]["tooling"][i].value === "withouttooling" && document.forms[1]["tooling"][i].checked === true) order_total = order_total * ".30";
if (document.forms[1]["tooling"][i].value === "withtooling" && document.forms[1]["tooling"][i].checked === true) order_total = order_total * ".40";
}
//order_total = order_total * .35
order_total = order_total + 25;
} else {
order_total = 0;
}

// Display the total rounded to two decimal places
//frm.totalcost.value = '$ ' + round_decimals(order_total, 2);
document.forms[1]["totalcost"].value = '$' + _N(order_total, 2);
_CalculateTotal();
}

function _CalculateTotal() {
var $grandTotal = 0;
var $f = document.forms[1];
for(var $i = 0; $i < $itemCount; $i++) {
$grandTotal = ($grandTotal) + parseFloat($f[$tFields[$i]].value.replace(/[^0-9.]/g, ""));
}
document.getElementById("grandTotal").innerHTML = _N($grandTotal, 2);
}
[/CODE]


This code should work, but to be fair it hasn't been tested. I should also note that I'm using [B]document.forms[1][/B] which is only done as your actual page seems to have another form on it, making the order form the second form (1 instead of 0). If the order form were the only form on the page it should be using [B]document.forms[0][/B] instead. And again as I mentioned earlier, a more proper way to do this would be to assign a '[I]name[/I]' attribute to the [B]<form>[/B] tag and instead use that ([B]document.forms["formName"][/B]).

In order to use this new version of the function you will also have to change how you call the function. So for your first item you'd have something like
[code=html]
<input class="short" onchange="Calculate(0)" name="width">
[/code]

And for the second item you'd use
[code=html]
<input class="short" onchange="Calculate(1)" name="width">
[/code]

And so on for each new item (the same scheme applies to the length.

Lastly, I'll talk about the extra variables I added at the top. [B]$itemCount[/B] could be set dynmaically, so that when you say, change a drop down to choose the number of items you want, this number would update. It's currently used to calculate the grand total (so that it loops through all available items). The other 3 variables are arrays that hold field names. There was probably a 'better' way to go about this, but I found it to be a simple solution for your specific case. Those arrays would need to be updated if you added more than 4 items for instance, or if the '[I]name[/I]' attribute was different than what I have listed there.
Copy linkTweet thisAlerts:
@sherryrauthorApr 25.2014 — Thank you very much for taking the time to write this. I will plug it in today and test it out ?

Is there any chance it can be changed so that there is a quantity drop down (only up to 3 items ) If more than 1 item is selected then 2 different width and height fields will show up. My requirements have changed a bit..

If a customer chooses 1 item then they put in the width height, colour, tooling.

If a customer chooses 2 or 3 items the colour and tooling will not change but they can enter up to 3 different height and widths options. From what I understand if they choose tooling on item 1 then item 2 and 3 will automatically have tooling selected as well (factored in for pricing)
Copy linkTweet thisAlerts:
@Sup3rkirbyApr 25.2014 — Right now none of the changes I've posted here include a dropdown to control the number of items. Because your form is very... specific, it would take a little bit of time to rework the form to function dynamically (changing the number of items displayed).

The function I most recently posted simply was designed so that you can calculate the total and grand total regardless of the number of items. The same function will calculate the total of any individual item and loop through all available items to get a grand total. So it would work for 1 item or 15 items, it's just a matter of having the proper [B]<input>[/B] fields in your form and setting the [B]$itemCount[/B] variable when items are added or removed from the form.

If you make the changes you want in regard to 1 set of tooling options and then multiple width/length fields I can try working with that. But first I'd say it's a matter of at least getting your form the way you want it (functionality aside) and I could write a function to show/hide the extra width/length fields based on the number of items selected.
Copy linkTweet thisAlerts:
@sherryrauthorApr 25.2014 — Hi, I attempted to implement the code you gave me and it didn't work. Here is what I did.

1. Added your code above to the existing js file.

2. In Javascript file changed the form number from 1 to 0 since there is only 1 form

3. for 2 items added

<input class="short" onchange="Calculate(0)" name="width">

<input class="short" onchange="Calculate(0)" name="length">

*little unsure where to put form document.forms reference in html and where the $itemCount come into play.

<input class="short" onchange="Calculate(1)" name="width">

<input class="short" onchange="Calculate(1" name="lenght">

what did I miss?
Copy linkTweet thisAlerts:
@Sup3rkirbyApr 25.2014 — Okay, a couple of things to note here. Firstly, if this is going on your order form test page that you linked earlier, you actually do have 2 forms (the first one is the newsletter subscription form at the top of the page). So you may need to keep the form reference number at 1 rather than 0. Alternatively, you can just add a name="" value to the form and then use something like
[CODE]
document.forms["myFormName"]["length"].value;
[/CODE]

This would use the form object if you set the name attribute to 'myFormName', rather than trying to reference the form via index. Since there wasn't already a name on the form I just used the index for simplicity (less work for you).

Next, [B]$itemCount[/B] won't be messed with currently. Your form has 2 items and that doesn't change. I know you wish to change this soon, but based on the current form the number of items doesn't change, so [B]$itemCount[/B] can be left at 2 (which it is by default).

Lastly, it looks like I have trouble spelling from time to time. There was a mistake in my code (calling [B][I]$lFiends[/I][/B] and [B][I]$wFiends[/I][/B] instead of the correct variable names: [B]$lFields[/B] and [B]$wFields[/B]). Here's the corrected version:
[CODE]
if(typeof(_N) != "function") function _N($n, $d) { return ($d) ? Number($n).toFixed($d).toString().replace(/B(?=(d{3})+(?!d))/g, ",") : $n.toString().replace(/B(?=(d{3})+(?!d))/g, ","); }

$itemCount = 2;
$lFields = ["length", "length2", "length3", "length4"];
$wFields = ["width", "width2", "width3", "width4"];
$tFields = ["totalcost", "totalcost2", "totalcost3", "totalcost4"];

function Calculate($a) {
var order_total, length, width, i;
order_total = 0;

length = parseFloat(document.forms[1][$lFields[$a]].value);
width = parseFloat(document.forms[1][$wFields[$a]].width.value);

if(length > 0 && width > 0) {
order_total = length * width;
for(i = 0; i < document.forms[1]["tooling"].length; i++) {
if (document.forms[1]["tooling"][i].value === "withouttooling" && document.forms[1]["tooling"][i].checked === true) order_total = order_total * ".30";
if (document.forms[1]["tooling"][i].value === "withtooling" && document.forms[1]["tooling"][i].checked === true) order_total = order_total * ".40";
}
//order_total = order_total * .35
order_total = order_total + 25;
} else {
order_total = 0;
}

// Display the total rounded to two decimal places
//frm.totalcost.value = '$ ' + round_decimals(order_total, 2);
document.forms[1]["totalcost"].value = '$' + _N(order_total, 2);
_CalculateTotal();
}

function _CalculateTotal() {
var $grandTotal = 0;
var $f = document.forms[1];
for(var $i = 0; $i < $itemCount; $i++) {
$grandTotal = ($grandTotal) + parseFloat($f[$tFields[$i]].value.replace(/[^0-9.]/g, ""));
}
document.getElementById("grandTotal").innerHTML = _N($grandTotal, 2);
}
[/CODE]
Copy linkTweet thisAlerts:
@sherryrauthorApr 26.2014 — I added the modified code leaving the reference number to 1 but nothing happens on my form. I am missing something.

js code

if(typeof(_N) != "function") function _N($n, $d) { return ($d) ? Number($n).toFixed($d).toString().replace(/B(?=(d{3})+(?!d))/g, ",") : $n.toString().replace(/B(?=(d{3})+(?!d))/g, ","); }

function Calculate(frm) {

var order_total, length, width, i;

order_total = 0;

length = parseFloat(frm.length.value);
width = parseFloat(frm.width.value);

if(length > 0 && width > 0) {
order_total = length * width;
for(i = 0; i < frm.tooling.length; i++) {
if (frm.tooling[i].value === "withouttooling" && frm.tooling[i].checked === true) order_total = order_total * ".35";
if (frm.tooling[i].value === "withtooling" && frm.tooling[i].checked === true) order_total = order_total * ".45";
}
//order_total = order_total * .35
order_total = order_total
} else {
order_total = 0;
}

// Display the total rounded to two decimal places
//frm.totalcost.value = '$ ' + round_decimals(order_total, 2);
frm.totalcost.value = '$' + _N(order_total, 2);
_CalculateTotal(frm);

}


function Calculateitem2(frm) {

var order_total, length, width, i;

order_total = 0;

length = parseFloat(frm.length2.value);
width = parseFloat(frm.width2.value);

if(length > 0 && width > 0) {
order_total = length * width;
for(i = 0; i < frm.tooling2.length; i++) {
if(frm.tooling2[i].value === "withouttooling" && frm.tooling2[i].checked === true) order_total = order_total * ".35";
if(frm.tooling2[i].value === "withtooling" && frm.tooling2[i].checked === true) order_total = order_total * ".45";
}
//order_total2 = order_total2 * .35
order_total = order_total;
} else {
order_total = 0;
}

// Display the total rounded to two decimal places
//frm.totalcost2.value = '$ ' + round_decimals(order_total, 2);
frm.totalcost2.value = '$' + _N(order_total, 2);
_CalculateTotal(frm);

}

function _CalculateTotal($f) {

var $total1 = parseFloat($f.totalcost.value.replace(/[^0-9.]/g, ""));

var $total2 = parseFloat($f.totalcost2.value.replace(/[^0-9.]/g, ""));

console.log($total1, $total2);

document.getElementById("grandTotal").innerHTML = (!isNaN($total1) && !isNaN($total2)) ? "$" + _
N($total1 + $total2, 2) : "";

}

function round_decimals(original_number, decimals) {

var result1 = original_number * Math.pow(10, decimals);

var result2 = Math.round(result1);

var result3 = result2 / Math.pow(10, decimals);

return pad_with_zeros(result3, decimals);

}

function pad_with_zeros(rounded_value, decimal_places) {

// Convert the number to a string

var value_string = rounded_value.toString();

// Locate the decimal point
var decimal_location = value_string.indexOf(".");

// Is there a decimal point?
if(decimal_location == -1) {
// If no, then all decimal places will be padded with 0s
decimal_part_length = 0;

// If decimal_places is greater than zero, tack on a decimal point
value_string += decimal_places > 0 ? "." : "";
} else {
// If yes, then only the extra decimal places will be padded with 0s
decimal_part_length = value_string.length - decimal_location - 1;
}

// Calculate the number of decimal places that need to be padded with 0s
var pad_total = decimal_places - decimal_part_length;

if(pad_total > 0) {
// Pad the string with 0s
for(var counter = 1; counter <= pad_total; counter++) {
value_string += "0";
}
}
return value_string;

}

if(typeof(_N) != "function") function _N($n, $d) { return ($d) ? Number($n).toFixed($d).toString().replace(/B(?=(d{3})+(?!d))/g, ",") : $n.toString().replace(/B(?=(d{3})+(?!d))/g, ","); }

$itemCount = 2;

$lFields = ["length", "length2", "length3", "length4"];

$wFields = ["width", "width2", "width3", "width4"];

$tFields = ["totalcost", "totalcost2", "totalcost3", "totalcost4"];

function Calculate($a) {

var order_total, length, width, i;

order_total = 0;

length = parseFloat(document.forms[1][$lFields[$a]].value);
width = parseFloat(document.forms[1][$wFields[$a]].width.value);

if(length > 0 && width > 0) {
order_total = length * width;
for(i = 0; i < document.forms[1]["tooling"].length; i++) {
if (document.forms[1]["tooling"][i].value === "withouttooling" && document.forms[1]["tooling"][i].checked === true) order_total = order_total * ".30";
if (document.forms[1]["tooling"][i].value === "withtooling" && document.forms[1]["tooling"][i].checked === true) order_total = order_total * ".40";
}
//order_total = order_total * .35
order_total = order_total + 25;
} else {
order_total = 0;
}

// Display the total rounded to two decimal places
//frm.totalcost.value = '$ ' + round_decimals(order_total, 2);
document.forms[1]["totalcost"].value = '$' + _N(order_total, 2);
_CalculateTotal();

}

function _CalculateTotal() {

var $grandTotal = 0;

var $f = document.forms[1];

for(var $i = 0; $i < $itemCount; $i++) {

$grandTotal = ($grandTotal) + parseFloat($f[$tFields[$i]].value.replace(/[^0-9.]/g, ""));

}

document.getElementById("grandTotal").innerHTML = _
N($grandTotal, 2);

}

form same as before but input length and width replaced as referenced above.

http://www.webcrawldesigns.com/dct/order-form-test/

thx
Copy linkTweet thisAlerts:
@Sup3rkirbyApr 26.2014 — You are using the same names for each field, so it's hitting an error. Your first width and length field should be named like they currently are. The second width and length field should be called "width2" and "length2" (respectively). Just correct the name values and it should work.
Copy linkTweet thisAlerts:
@sherryrauthorApr 27.2014 — I changed the width and length to 2 and now it looks like it is registering but shows total cost of item one for example as $0.00 and grand total is NaN
Copy linkTweet thisAlerts:
@Sup3rkirbyApr 27.2014 — Alright, two things need to be adjusted. I did just notice two more issues with the code I gave you. I wasn't setting the width value correctly (thus the $0.00 price). The item total also wasn't set to write to each total box dynamically, so it only worked for the first item. Both are fixed in the code below:
[CODE]
function Calculate($a) {
var order_total, length, width, i;
order_total = 0;

length = parseFloat(document.forms[1][$lFields[$a]].value);
width = parseFloat(document.forms[1][$wFields[$a]].value);

if(length > 0 && width > 0) {
order_total = length * width;
for(i = 0; i < document.forms[1]["tooling"].length; i++) {
if (document.forms[1]["tooling"][i].value === "withouttooling" && document.forms[1]["tooling"][i].checked === true) order_total = order_total * ".30";
if (document.forms[1]["tooling"][i].value === "withtooling" && document.forms[1]["tooling"][i].checked === true) order_total = order_total * ".40";
}
//order_total = order_total * .35
order_total = order_total + 25;
} else {
order_total = 0;
}

// Display the total rounded to two decimal places
//frm.totalcost.value = '$ ' + round_decimals(order_total, 2);
document.forms[1][$tFields[$a]].value = '$' + _N(order_total, 2);
_CalculateTotal();
}
[/CODE]



As for the NaN grand total. This is because not all of the total boxes have a total/value when the grand total is being calculated. This can be fixed a few different ways. The easiest way is to have a default value in those total boxes. Since those inputs have an empty string, it fails to pull a total to add and thus the result is indeed not a number (aka NaN).

But since it's also a best practice to have the code check and correct all issues, I've modified my grand total function as well:
[CODE]
function _CalculateTotal() {
var $grandTotal = 0;
var $f = document.forms[1];
for(var $i = 0; $i < $itemCount; $i++) {
var $tmpTotal = parseFloat($f[$tFields[$i]].value.replace(/[^0-9.]/g, ""));
$grandTotal = (isNaN($tmpTotal)) ? ($grandTotal) + 0 : ($grandTotal) + $tmpTotal;
}
document.getElementById("grandTotal").innerHTML = _N($grandTotal, 2);
}
[/CODE]


Though I still feel there should be a default value in those total boxes.
Copy linkTweet thisAlerts:
@sherryrauthorApr 28.2014 — Now we are getting somewhere ? thanks for this. I have a few questions.

1. Can I have the no tooling selected for all 3 items ? I attempted to change the value for tooling to tooling2 and tooling3 but that didn't do it.

2. You mentioned something about passing the grandTotal variable via .php to email not an option.. how do you suggest going about sending the values to an email where I can pick up the grandTotal amount?

Thanks
Copy linkTweet thisAlerts:
@Sup3rkirbyApr 28.2014 — So, another thing I noticed in my code that doesn't coincide well with your actual page is the tooling options. The ability to have separate tooling options (and thus tooling calculations) per item can be added into the function, however I was under the impression you were headed in the direction of having 1 set of tooling options and the only duplicated elements on the form would be the length and width boxes (one set per item). This is currently how the [B]_Calculate()[/B] function operates. So depending on how you are going to do this in the form, I can either modify the javascript, or the form itself will have to be changed to only show 1 set of tooling options.

And regarding your second question, currently the grand total is not being put into an [B]<input>[/B] element in the form. This means when the form is submitted the grand total is not passed to PHP. Again, I strongly feel that while it's important to preform these totaling calculations on the user's end (javascript) to allow them to see their totals, the actual totals to be send to an email or database should be calculated in PHP. The same way you calculate these things in javascript, you would do this on the PHP side of things, reading the length and width of all submitted fields as well as the tooling option choice.

From a very basic standpoint though, you could simply use PHP to add the two submitted totals together. I have no idea what your PHP looks like, but you'd be doing something like this:
[code=php]
$totalcost = (isset($_POST["totalcost"])) ? (int)preg_replace("/[^0-9.]/", "", $_POST["totalcost"]) : 0;
$totalcost2 = (isset($_POST["totalcost2"])) ? (int)preg_replace("/[^0-9.]/", "", $_POST["totalcost2"]) : 0;

$grandTotal = $totalcost + $totalcost2;
[/code]

But keep in mind that's a very basic way of handling this. Realistically you would actually just take the width, length and tooling option values into your PHP and then recalculate the totals. This would give you the most accurate and reliable totals.
Copy linkTweet thisAlerts:
@sherryrauthorApr 28.2014 — and then $grandTotal could be passed to email from php rather then form?

I will post up my new requirements shorty, I want to fully understand them so I don't waste your time.

Thx
Copy linkTweet thisAlerts:
@sherryrauthorApr 29.2014 — Ok I think I have it all defined now.. when you get time could you modify the code so that this happens.

On from quantity drop down 1 - 3 (items max)

width / height

no tooling / tooling

totalcost

grand total

IF quantity of 2 is selected an extra width and height and total cost2 field appears above grand total. *whatever was selected for tooling in item 1 will be the same.

IF quantity of 3 is selected an same thing would happen but would show 2 height, width and total costs above grand total.

so potentially the form could look like this

quantity 3 selected

item 1 - width / height

no tooling / tooling

total cost

item 2 - width / height

totalcost2

item 3 width / height

totalcost 3

grand total

thanks again.
Copy linkTweet thisAlerts:
@sherryrauthorApr 30.2014 — one more thing to add.. would be good if there was a quantity button beside items numbers in case someone wants to order 2 items as an example with the same width and height ?
Copy linkTweet thisAlerts:
@sherryrauthorMay 02.2014 — Hello, any chance you can come up with the new code next week based on last 2 posts?

Thx
Copy linkTweet thisAlerts:
@Sup3rkirbyMay 02.2014 — If '[I]the next week[/I]' means one week from today then I'm certain I can have some new code by then.

Though I do feel I should mention, I don't want you or anyone to get the wrong idea. Generally post like this are things to avoid as it's essentially free, non-contracted work on sites that I have no affiliation or stake in (aka [B]Free[/B]lance). Most things I answer on here are fairly simple things that I can deal with in a matter of minutes. And occasionally things take a bit more effort as the actual issues are more complex. But I post here because I enjoy web development and certainly don't mind helping those willing to learn in this industry.

That being said, your issue here isn't complex but rather, time consuming, as it's a full solution or rather an effective replacement of something that already existed. Again, I don't mind helping but please keep in mind this is me in my free time offering what knowledge and assistance I can to those who could benefit from it. I'll try to take time today to dig into your order form, and I'll likely complete it today.
Copy linkTweet thisAlerts:
@Sup3rkirbyMay 03.2014 — This will probably be a little messy. Throughout this thread the code has changed a bit and I've done my work on several computers (so I was updating an older version that was on this PC). Also, the biggest thing I didn't want to deal with was the HTML/formatting of this form. So with that aside, understand this code works, but cannot be directly copied into your page as it'll likely break something. But if you're careful, you can take out the parts and place them as you see fit. As long as the core of this is on your page and the script is the same, it should work.

[code=html]
Number of Items:
<select id="itemCount" name="itemCount" onchange="_ChangeItemCount(this)">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<br />
<br />
<p><input class="checkbox" value="withouttooling" checked="checked" name="tooling" type="radio"> No Tooling Design<br/><br />
<input class="checkbox" value="withtooling" name="tooling" type="radio"> With tooling design<br/><br />
<small style="FONT: 10px Arial,Helvetica,sans-serif">(All tooling Gold unless otherwise specified)</small></p>
<p>Tooling design inset<br/><br />
Choose<br />
<input class="checkbox" value="1/2 inch" name="inset" type="radio"> 1/2&#8221;<br />
<input class="checkbox" value="3/4 inch" name="inset" type="radio"> 3/4&#8221;<br />
<input class="checkbox" value="1 inch" name="inset" type="radio"> 1&#8221;</p>
<p>Plus $25.00 shipping</p>
<hr/>
<br />

<div id="itemDiv1">
<strong>Item 1</strong>
<br />
Width<br />
<input class="short" onchange="Calculate(1)" name="width1"><small>(in)</small>
<br/><br />
Length<br />
<input class="short" onchange="Calculate(1)" name="length1"><small>(in)</small>
<p style="PADDING-BOTTOM: 0pt"><strong>Total Cost</strong><input class="short" onfocus="this.form.elements[0].focus()" name="totalcost1" id="totalcost1" /></p>
</div>


<div id="itemDiv2">
<strong>Item 2</strong>
<br />
Width<br />
<input class="short" type="text" name="width2" onchange="Calculate(2)" /><small>(in)</small>
<br /><br />
Length<br />
<input class="short" type="text" name="length2" onchange="Calculate(2)" /><small>(in)</small>
<p style="PADDING-BOTTOM: 0pt"><strong>Total Cost</strong><input class="short" onfocus="this.form.elements[0].focus()" name="totalcost2" id="totalcost2" /></p>
</div>


<div id="itemDiv3">
<strong>Item 3</strong>
<br />
Width<br />
<input class="short" type="text" name="width3" onchange="Calculate(3)" /><small>(in)</small>
<br /><br />
Length<br />
<input class="short" type="text" name="length3" onchange="Calculate(3)" /><small>(in)</small>
<p style="PADDING-BOTTOM: 0pt"><strong>Total Cost</strong><input class="short" onfocus="this.form.elements[0].focus()" name="totalcost3" id="totalcost3" /></p>
</div>


<br />
<br />

Grand Total: <span id="grandTotal"></span>

<script>
if(typeof(_N) != "function") function _N($n, $d) { return ($d) ? Number($n).toFixed($d).toString().replace(/B(?=(d{3})+(?!d))/g, ",") : $n.toString().replace(/B(?=(d{3})+(?!d))/g, ","); }

$itemCount = 1;

function _ChangeItemCount($a) {
$itemCount = $a.value;
document.getElementById("itemDiv1").style.display = "none";
document.getElementById("itemDiv2").style.display = "none";
document.getElementById("itemDiv3").style.display = "none";
for(var $i = 0; $i < $itemCount; $i++) {
document.getElementById("itemDiv"+($i+1)).style.display = "block";
}
_CalculateTotal();
}
_ChangeItemCount(document.getElementById("itemCount"));

function Calculate($a) {
var order_total, length, width, i;
order_total = 0;

length = parseFloat(document.forms[1]["length"+$a].value);
width = parseFloat(document.forms[1]["width"+$a].value);

if(length > 0 && width > 0) {
order_total = length * width;
for(i = 0; i < document.forms[1]["tooling"].length; i++) {
if (document.forms[1]["tooling"][i].value === "withouttooling" && document.forms[1]["tooling"][i].checked === true) order_total = order_total * ".30";
if (document.forms[1]["tooling"][i].value === "withtooling" && document.forms[1]["tooling"][i].checked === true) order_total = order_total * ".40";
}
order_total = order_total + 25;
} else {
order_total = 0;
}


document.forms[1]["totalcost"+$a].value = '$' + _N(order_total, 2);
_CalculateTotal();
}

function _CalculateTotal() {
var $grandTotal = 0;
var $f = document.forms[1];
for(var $i = 0; $i < $itemCount; $i++) {
var $tmpTotal = parseFloat($f["totalcost"+($i+1)].value.replace(/[^0-9.]/g, ""));
$grandTotal = (isNaN($tmpTotal)) ? ($grandTotal) + 0 : ($grandTotal) + $tmpTotal;
}
document.getElementById("grandTotal").innerHTML = _N($grandTotal, 2);
}
</script>
[/code]


This is pretty simple overall, but to explain (so you know what you're getting and what to expect), this has a dropdown/select element at the top. When you change this, a new function will show/hide the number items (currently set at a max of 3). Each 'item' display includes a width, length and totalcost field. Each of these items functions independently, with their own values and prices. The tooling and options are at the top, but not part of any specific item (so the value is applied to all items). The grand total calculates the total based on which items are currently visible/available.

Again, be careful when adding this code. I didn't copy your entire form so the actual HTML part needs to be inserted as you feel it should be placed on your form. The javascript can be copied directly with no issues.
Copy linkTweet thisAlerts:
@sherryrauthorMay 04.2014 — Hi, thanks for helping with this.

I added this to a new page just to test and items 2 and 3 appear to be showing all the time. (doesn't matter how many items are selected)

I added html head body and form tags (just didn't spend time formatting)

I removed the newsletter form off of my site so I think I needed to change form name from 1 to 0.

This is the page I have it plugged into - http://www.webcrawldesigns.com/dct/new-code/


This is the code in the page

if(typeof(_N) != "function") function _N($n, $d) { return ($d) ? Number($n).toFixed($d).toString().replace(/B(?=(d{3})+(?!d))/g, ",") : $n.toString().replace(/B(?=(d{3})+(?!d))/g, ","); }

$itemCount = 1;

function _ChangeItemCount($a) {

$itemCount = $a.value;

document.getElementById("itemDiv1").style.display = "none";

document.getElementById("itemDiv2").style.display = "none";

document.getElementById("itemDiv3").style.display = "none";

for(var $i = 0; $i < $itemCount; $i++) {

document.getElementById("itemDiv"+($i+1)).style.display = "block";

}

_
CalculateTotal();

}

_ChangeItemCount(document.getElementById("itemCount"));

function Calculate($a) {

var order_total, length, width, i;

order_total = 0;

length = parseFloat(document.forms[0]["length"+$a].value);
width = parseFloat(document.forms[0]["width"+$a].value);

if(length > 0 && width > 0) {
order_total = length * width;
for(i = 0; i < document.forms[0]["tooling"].length; i++) {
if (document.forms[0]["tooling"][i].value === "withouttooling" && document.forms[0]["tooling"][i].checked === true) order_total = order_total * ".30";
if (document.forms[0]["tooling"][i].value === "withtooling" && document.forms[0]["tooling"][i].checked === true) order_total = order_total * ".40";
}
order_total = order_total + 25;
} else {
order_total = 0;
}


document.forms[0]["totalcost"+$a].value = '$' + _N(order_total, 2);
_CalculateTotal();

}

function _CalculateTotal() {

var $grandTotal = 0;

var $f = document.forms[0];

for(var $i = 0; $i < $itemCount; $i++) {

var $tmpTotal = parseFloat($f["totalcost"+($i+1)].value.replace(/[^0-9.]/g, ""));

$grandTotal = (isNaN($tmpTotal)) ? ($grandTotal) + 0 : ($grandTotal) + $tmpTotal;

}

document.getElementById("grandTotal").innerHTML = _
N($grandTotal, 2);

}
Copy linkTweet thisAlerts:
@Sup3rkirbyMay 04.2014 — What are you using to edit this page or upload your code? There are a bunch of [B]<p>[/B] tags (opening and closing) inside of the javascript. This is causing an error (syntax), thus none of the javascript can run, so things like totaling and showing/hiding items won't work.
Copy linkTweet thisAlerts:
@sherryrauthorMay 05.2014 — Hi, strange I removed <P> references and doesn't work but might be how WP editor handles code?

I did paste in regular html page -http://www.webcrawldesigns.com/dct/_ordertest.html

and it looks like it works except is there any way to make it so when the page loads only item 1 width and height shows instead of all 3? (until selection is made)
Copy linkTweet thisAlerts:
@Sup3rkirbyMay 05.2014 — The script will automatically hide the additional fields, however you are currently loading the script ([I]calculatornew1.js[/I]) before the HTML of the form is loaded (thus it hits an error as the [B]<select>[/B] element doesn't exist yet.

To be fair, in the name of standards the code should be able to adapt to such situations so there is one line that should be changed to fix this on the script's end. Change:
[CODE]
_ChangeItemCount(document.getElementById("itemCount"));
[/CODE]

To:
[CODE]
window.onload = function() {_ChangeItemCount(document.getElementById("itemCount")); }
[/CODE]


That should fix the issue of not hiding the extra items when the page loads. I feel I should also mention that it's generally a good idea to include javascript files at the end of your document. When a script file is loaded, unless the async property is set to true, the page will stop loading all other data until the script has finished loading. Thus scripts included in the [B]<head>[/B] or above any content tend to be a bad idea logically, as it can slow down load times (while generally unnoticeable, it should still be avoided for the sake of standards).
Copy linkTweet thisAlerts:
@sherryrauthorMay 05.2014 — Actually when I moved the script down on the page it did only show 1 when the page loaded thanks for that.

OK hopefully my final question (I do appreciate your help) ?

I have the calculation working thanks to you and when I add the drop down code to the page with working calculations page I cannot get both to work.

WORKING CALCULATION CODE

http://www.webcrawldesigns.com/dct/wp-includes/js/calculatornew.js


WORKING DROP DOWN CODE

http://www.webcrawldesigns.com/dct/wp-includes/js/calculatornew1.js


but can't get both functions to work on the same page...

http://www.webcrawldesigns.com/dct/order-form/
Copy linkTweet thisAlerts:
@sherryrauthorMay 06.2014 — Would there be a reason I couldnt' run both scripts on 1 page? Or is the problem with the grand total (because on both?)
Copy linkTweet thisAlerts:
@Sup3rkirbyMay 06.2014 — On your 'combined' page (http://www.webcrawldesigns.com/dct/order-form/) I'm still seeing [B]<p>[/B] tags inside of the javascript. I assume this is why the script doesn't appear to be working on that page. Try removing those tags from the script and see if that fixes the issue.
Copy linkTweet thisAlerts:
@sherryrauthorMay 07.2014 — I have a working page with select drop down and calculated totals - thanks ?

Only thing that isn't working now is the remember js I plugged in (and was working before)

http://www.webcrawldesigns.com/dct/order-form

remember js script

function _SaveFields($a) {

if(localStorage !== null && localStorage !== undefined) {

localStorage.setItem("company", $a["company"].value);

localStorage.setItem("contact", $a["contact"].value);

localStorage.setItem("address", $a["address"].value);

localStorage.setItem("city", $a["city"].value);

localStorage.setItem("state", $a["state"].value);

localStorage.setItem("Zip", $a["Zip"].value);

localStorage.setItem("phone", $a["phone"].value);

localStorage.setItem("email", $a["email"].value);

localStorage.setItem("shipping", $a["shipping"].value);

localStorage.setItem("comments", $a["comments"].value);

}

}

window.onload = function() {

if(localStorage !== null && localStorage !== undefined) {

document.forms[1]["company"].value = (localStorage.getItem("company") !== null && localStorage.getItem("company") !== undefined) ? localStorage.getItem("company") : "";

document.forms[1]["contact"].value = (localStorage.getItem("contact") !== null && localStorage.getItem("contact") !== undefined) ? localStorage.getItem("contact") : "";

document.forms[1]["address"].value = (localStorage.getItem("address") !== null && localStorage.getItem("address") !== undefined) ? localStorage.getItem("address") : "";

document.forms[1]["city"].value = (localStorage.getItem("city") !== null && localStorage.getItem("city") !== undefined) ? localStorage.getItem("city") : "";

document.forms[1]["state"].value = (localStorage.getItem("state") !== null && localStorage.getItem("state") !== undefined) ? localStorage.getItem("state") : "";

document.forms[1]["Zip"].value = (localStorage.getItem("Zip") !== null && localStorage.getItem("Zip") !== undefined) ? localStorage.getItem("Zip") : "";

document.forms[1]["phone"].value = (localStorage.getItem("phone") !== null && localStorage.getItem("phone") !== undefined) ? localStorage.getItem("phone") : "";

document.forms[1]["email"].value = (localStorage.getItem("email") !== null && localStorage.getItem("email") !== undefined) ? localStorage.getItem("email") : "";

document.forms[1]["shipping"].value = (localStorage.getItem("shipping") !== null && localStorage.getItem("shipping") !== undefined) ? localStorage.getItem("shipping") : "";

document.forms[1]["comments"].value = (localStorage.getItem("comments") !== null && localStorage.getItem("comments") !== undefined) ? localStorage.getItem("comments") : "";

}

}
Copy linkTweet thisAlerts:
@Sup3rkirbyMay 07.2014 — The part of that script that runs to restore any saved values is referencing '[B]document.forms[1][/B]' but currently there is only one form on the page now so that should be updated to '[B]document.forms[0][/B]' and everything should be working then.
Copy linkTweet thisAlerts:
@sherryrauthorMay 08.2014 — Thanks that did it.. I notice that when I change the selection from tooling to notooling the total cost doesn't change.

Can you take a quick look at this please www.webcrawldesigns.com/dct/order-form

thanks
Copy linkTweet thisAlerts:
@JMRKERMay 08.2014 — Thanks that did it.. I notice that when I change the selection from tooling to notooling the total cost doesn't change.

Can you take a quick look at this please www.webcrawldesigns.com/dct/order-form

thanks[/QUOTE]


Some might think you are starting to abuse the generosity of Sup3rkirby.

You should at least look at the code provided and give a guess as to what should or would be changed to accomplish your requirements. Otherwise you will spend the rest of your career like Stella in "A Streetcar Named Desire" always relying on the "generosity of strangers".
Copy linkTweet thisAlerts:
@sherryrauthorMay 08.2014 — Actually it is not like that. I appreciate the help and I am learning as I go.
Copy linkTweet thisAlerts:
@Sup3rkirbyMay 12.2014 — [B][I]"Stellaaaaaaaaaaa!"[/I][/B]

Perhaps you have since fixed the issue, but I'm not noticing that problem on the page. Switching between the two tooling options seems to change the price accordingly.

I will note that generally your questions are easy enough to where I don't mind helping, but you should know there is no secret magic behind what I do. Generally when a script doesn't work I open the page where it should be running, press F12 and go to the 'Console' tab. If the script is truly broken I'll see an error that I can link back to a specific line in the script. If there are no errors I know it's more of a logical flaw in the script.

It's an invaluable tool built into modern browsers that can likely help you solve most of the problems you may encounter. For instance, you'll be able to pick up on a number of other errors that are occurring on the page, such as your remember.js file trying to set the value of your 'shipping' field which does not exist.
×

Success!

Help @sherryr spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 6.2,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @meenaratha,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,

tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,
)...