Javascript Calculations not working in IE8 and below Pleeeeease Help

This must be the most commonly asked question yet I could not find the answer to my problem.

I have a script to perform some simple calculations on my site and everything works fine on all browsers, but not in IE8 or below. I searched the whole world for an answer, but couldn’t find it, but then I saw one of you solving a similar problem here. So I thought I would ask.

I have this following as the DOCTYPE

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html lang="en-US">

The script stopped working also when I change to strict.dtd.

Here is the script in question:
<script language="javascript" type="text/javascript">
<!--
function TotalOrder()
{
//document.getElementById('itemsToTotal').innerHTML = "";

var A = parseInt(document.getElementById('FR1').value) || 0;
var B = parseInt(document.getElementById('FR2').value) || 0;
var C = parseInt(document.getElementById('FR3').value) || 0;
var D = parseInt(document.getElementById('SR1').value) || 0;
var E = parseInt(document.getElementById('SR2').value) || 0;

var orderplaced = A + B + C + D + E;
document.getElementById('ORDERPLACED').innerHTML = orderplaced;
}
// -->
</script>

============================================
Supposed to add the values of few fields and show the total items selected. But all I get is a zero for the value. It is doing something but the answer is always Zero.

I am using text/javascript.
Should I change the single quotes to double quotes for FR1,2 etc and for ORDERPLACED id tags?

Any help would be greatly appreciated. I can send you the complete code and link in a separate email.

Thank you.

Hi there,
If you could post the complete code or a link to a page where I can see this, I don’t mind having a look for you.

Pullo, can I send the link to you in an email. I just don’t want to place it in public forum since it is a working site.

Ok, could you post a better code example, then?
Basically a boiled down example which I can copy and paste to reproduce your error.

Please send an email to …
As soon as I get your email, I will delete it from here and then we can easily exchange files. Thank you.

Hi,
I’m sorry, but to be able to help you, I’d need to see the code here.
This is so that any solution to your problem can potentially help others in the future.
I understand if you don’t want to or are not able to post your code here.
Maybe someone else will be able to give you some help based on what you have already provided.

Indeed I understand that. The solution has to be available to everyone who follow this thread.
I will see if I can recreate a sample and post it here. The whole page is too cumbersome to post and don’t know if it would work for you with the links to all it’s styles, js etc. If I can create I’ll post it here. Thank you.

No problem.

This is what I mean by a boiled down example.
Just enough code to reproduce your problem, but nothing more.
This is also what I do personally when I run up against a coding problem. I find that this approach helps me to focus on the problem at hand and more often than not, producing a bare bones example of what’s not working, leads me to a solution, or at least points me in the right direction.

Okay, I created a sample page.
When you open the html and make a selection from the drop down, it is supposed to add the values and display that in the TOTAL box and then the embedded script should display the total number selected as well.
Both works fine on all browsers except IE8 and lower.

I am breaking on “frm.elements.length” is null or not an object???
And seem to be getting the same error as I step through the code.

Please let me know if you need anything else. Thank you.

Here is the page html:


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<script language="JavaScript" src="/js/form_calculations2.js" type="text/javascript"></script>
<script language="javascript" type="text/javascript">
<!--
function TotalOrder()
{
//document.getElementById('itemsToTotal').innerHTML = "";

var A = parseInt(document.getElementById("FR1").value) || 0;
var B = parseInt(document.getElementById("FR2").value) || 0;
var C = parseInt(document.getElementById("FR3").value) || 0;

var orderplaced = A + B + C;
document.getElementById("ORDERPLACED").innerHTML = orderplaced;
}
-->
</script>

<body>
<div style="width: 100%; float: left">


  <!-- End right GrandTotal panel -->
  <div style="width: 30%; height:160px; float: left;">
    <h3>FAMILY RATE <br>
      <span>($45 for the Family)</span></h3>
    <br clear="all" />
    <div>
      <div style="width: 140px; float: left;">ADULTS ($45)</div>
      <div style="width: 40px; float: left;">
        <select name="CHARGE_ADULT_4500" id="FR1" onKeyUp="CalculateTotal(this.form);TotalOrder()"  onChange="CalculateTotal(this.form);TotalOrder()">
          <option>0</option>
          <option>1</option>
          <option>2</option>
          <option>3</option>
          <option>4</option>
          <option>5</option>
        </select>
      </div>
    </div>
    <br clear="all"/>
    <div >
      <div style="width: 140px; float: left;">CHILDREN ($0)</div>
      <div style="width: 40px; float: left;">
        <select name="CHARGE_12UNDER_000" id="FR2" onKeyUp="CalculateTotal(this.form);TotalOrder()"  onChange="CalculateTotal(this.form);TotalOrder()">
          <option>0</option>
          <option>1</option>
          <option>2</option>
          <option>3</option>
          <option>4</option>
          <option>5</option>
        </select>
      </div>
    </div>
    <br clear="all"/>
    <div >
      <div style="width: 140px; float: left;" >CHILDREN ($0)</div>
      <div style="width: 40px; float: left;">
        <select name="CHARGE_6UNDER_000"  id="FR3" onKeyUp="CalculateTotal(this.form);TotalOrder()"  onChange="CalculateTotal(this.form);TotalOrder()">
          <option>0</option>
          <option>1</option>
          <option>2</option>
          <option>3</option>
          <option>4</option>
          <option>5</option>
        </select>
      </div>
    </div>
    <br clear="all" />
<br/>
    <div style="width: 180px;  background-color:#CCC; float: left;">
      <h4 >TOTAL  ATTENDING</h4>
      <div style="width: 20px; border: 1px solid rgb(0, 51, 102); BACKGROUND-COLOR: #f5f5f5; color: rgb(0, 51, 102);  id='ORDERPLACED'>&nbsp;</div> <br clear="all" /></div>
       <br/><br clear="all" />
       <div style="width: 40%;  background-color:#FFC; float: left; text-align: center">YOUR TOTAL:
      <input type="text" readonly name=GRNDTOTAL size=10 STYLE="border: 1px solid rgb(0, 51, 102); BACKGROUND-COLOR: #f5f5f5; color: rgb(0, 51, 102); font-size:16px;" onFocus="this.form.elements[0].focus()" />
    </div>
  </div>
</div>
</body>
</html>

And here is the form_calculation script (based on Paul McFedries’ script) that I am using (already linked in the HTML page)


// JavaScript Document
function CalculateTotal(frm) {
    var order_total = 0
	var btn_selected = 0
	
	order_total += 1 * parseFloat(btn_selected/100)
    // 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,6) == "CHARGE") {
            // If so, extract the price from the name
            item_price = parseFloat(form_name.substring(form_name.lastIndexOf("_") + 1))
			// Divide by 100 to get the price in dollars and cents.
            item_price = parseFloat(item_price/100)
            // Get the quantity
            item_quantity = parseInt(form_field.value)
            // Update the order total
            if (item_quantity >= 1) {				
				if (item_price == 45) {
					item_quantity = 1	
				}
                order_total += item_quantity * item_price
            }
        }
    }
    frm.GRNDTOTAL.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
}


//-->

Missing couple of lines from my HTML code

Add this line after body tag

  <form method="post" action="/forms/formMail/formMailEngine.php" name="myForm">

Then I also tried changing my TotalOrder() as follows, as I was seeing errors at getElementById, but that did not seem to help either.

<script language="javascript" type="text/javascript">
<!--
function TotalOrder()
{
//document.getElementById('itemsToTotal').innerHTML = "";

var A = parseInt(document.myForm("FR1").value) || 0;
var B = parseInt(document.myForm("FR2").value) || 0;
var C = parseInt(document.myForm("FR3").value) || 0;

var orderplaced = A + B + C;
document.myForm("ORDERPLACED").innerHTML = orderplaced;
}
-->
</script>

Hi there,

Thanks for trying to put together a more concise example. That’s a good start.
Unfortunately, when I try and run your code it doesn’t work in any browser.
From what I see of your code, it seems that you have two select menus where you can chose the number of adults and the number of children attending an event.
You are then trying to dynamically update the total cost based on what has been selected.
Instead of trying to debug your code, I put together a simple script which does what I have just described.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Calculate total order</title>
  </head>

  <body>
    <form>
      <div>
        <label for="adult">ADULTS ($45)</label>
        <select id="adult">
          <option>0</option>
          <option>1</option>
          <option>2</option>
          <option>3</option>
          <option>4</option>
          <option>5</option>
        </select>
      </div>
      
      <div>
        <label for="child">CHILDREN ($0)</label>
        <select id="child">
          <option>0</option>
          <option>1</option>
          <option>2</option>
          <option>3</option>
          <option>4</option>
          <option>5</option>
        </select>
      </div>
    </form>
    
    <p>
      <strong>Total</strong><br />
      People: <span id="people"></span><br />
      Cost: <span id="cost"></span>
    <p>
    
    <script>
      window.onload = function(){
        var sel = document.getElementsByTagName("select");
        var adult = document.getElementById("adult");
        var child = document.getElementById("child");
        var people = document.getElementById("people");
        var cost = document.getElementById("cost");
        
        function updateTotal(personType, personAmount){
          // Update number
          totalAdults = parseInt(adult.options[adult.selectedIndex].text);
          totalChildren = parseInt(child.options[child.selectedIndex].text);
          totalPeople =  totalAdults + totalChildren;
          peopleText = totalAdults + ' adults and ' + totalChildren + ' children (' + totalPeople + ' in total)';
          people.innerHTML = peopleText;
          
          // Update cost
          totalCost = totalAdults * 45;
          cost.innerHTML = '$' + totalCost;
        }
        
        for(var i=0; i<sel.length; i++) {
          sel[i].onchange = function(){updateTotal()};
        }
      };
    </script>
  </body>
</html>

Hopefully this will help you. It works in all browsers.

That is very kind of you. I will try it this evening. What I send you was only part of my calculations script, but I still need to add couple of more sections like that one for Single only at $10 a piece. Also for the family rate, the amount is fixed at $45 for the whole family. I will try to modify the code to get it working for my needs, because your code looks so simple and elegant. Thank you.

Well, I feel terrible. All I did was I tried to add couple of additional fields, updated script and for some reason it just wouldn’t cooperate with me.

Can you please take a look. Thank you.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Calculate total order</title>
</head>

<body>
<form>
  <div>
    <label for="adult">ADULTS ($25)</label>
    <select id="adult">
      <option>0</option>
      <option>1</option>
      <option>2</option>
      <option>3</option>
      <option>4</option>
      <option>5</option>
    </select>
  </div>
  <div>
    <label for="child">CHILDREN ($0)</label>
    <select id="child">
      <option>0</option>
      <option>1</option>
      <option>2</option>
      <option>3</option>
      <option>4</option>
      <option>5</option>
    </select>
  </div>
  <br/>
  <div>
    <label for="single">SINGLES ($10)</label>
    <select id="single">
      <option>0</option>
      <option>1</option>
      <option>2</option>
      <option>3</option>
      <option>4</option>
      <option>5</option>
    </select>
  </div>
  <div>
    <label for="child2">CHILDREN ($0)</label>
    <select id="child2">
      <option>0</option>
      <option>1</option>
      <option>2</option>
      <option>3</option>
      <option>4</option>
      <option>5</option>
    </select>
  </div>
</form>
<p> <strong>Total</strong><br />
  People: <span id="people"></span><br />
  Cost: <span id="cost"></span>
<p>
  <script type="text/javascript">
      window.onload = function(){
        var sel = document.getElementsByTagName("select");
        var adult = document.getElementById("adult");
        var child = document.getElementById("child");

        var single = document.getElementById("single");
        var child2 = document.getElementById("child2");
		
        var people = document.getElementById("people");
        var cost = document.getElementById("cost");

        function updateTotal(personType, personAmount){
          // Update number
	  	countAdults = parseInt(adult.options[adult.selectedIndex].text);
	  	countChild  = parseInt(child.options[child.selectedIndex].text);
	  	countSingle = parseInt(single.options[single.selectedIndex].text);
      		countChild2	= parseInt(child2.options[child2.selectedIndex].text);

	  if (countAdults) {
		costAdults = countAdults * 25;
	  }
	  else {
		costAdults = 0;
	  }
	  if (countSingle) {
		costSingle = countSingle * 10;
	  }
	  else {
		costSingle = 0;
	  }

	  totalAdults = costAdults + costSingle;
          totalChildren = countChild + countChild2;

          //totalAdults = parseInt(adult.options[adult.selectedIndex].text);
          //totalChildren = parseInt(child.options[child.selectedIndex].text);

          totalPeople =  countAdults + countChildren;
          peopleText = countAdults + ' adults and ' + countChildren + ' children (' + totalPeople + ' in total)';
          people.innerHTML = peopleText;

          // Update cost
          totalCost = totalAdults;
          cost.innerHTML = '$' + totalCost;
        }

        for(var i=0; i<sel.length; i++) {
        sel[i].onchange = function(){updateTotal()};
     }
  };
</script>
</body>
</html>

Hi there,

Your problem is in these twol ines:

totalPeople =  countAdults + countChildren;
peopleText = countAdults + ' adults and ' + countChildren + ' children (' + totalPeople + ' in total)';

countChildren is not defined anywhere.
Try changing it to countChild or something.

A little tip: get yourself some kind of JavaScript debugger to find errors like this.
If you are using Chrome, for example, press F12 and select the “Console” tab, then refresh the page.

I’m off to bed now. It’s late here.
Good luck!

Yes that was it. Thank you. Good night. God bless you.

I just have one more question, if I could ask… I wanted to pass the value of the total cost to another autoresponds form, how can I do that. I tried the following, but that is not quite working. I am not all that familiar with how to handle objects using javascript.

I have added a field GRNDTOTAL2 and then tried to call $GRNDTOTAL2 in the other form, but didn’t work.

I don’t know if I can pass the GRNDTOTAL in any other manner.


<span id=GRNDTOTAL  class=grandTotalTxt type="text" readonly size=10 STYLE="width: auto; float: right;  margin-right:5px;" /></span>
.....
<input type="hidden" name="GRNDTOTAL2">
......

totalCost = totalCostFRadults;
cost.innerHTML ='$' + totalCost + '.00';
document.getElementById("GRNDTOTAL2").value = totalCost;


Okay I am one more step closer… I was about to give up after trying so many different variants. With very little javascript knowledge, it just becomes a matter of trial and error.

With the code below I can display the value on the main page, but $GRNDTOTAL2 is not holding the value in the next page.

I kept the new hidden <input> field GRNDTOTAL2 and set its value as follows:


var display = document.getElementById("GRNDTOTAL2");
display.value = totalCost;

Hi there,

Do I understand you correctly: on form submission you want to pass a value calculated in JavaScript to a PHP script for processing?

Yes, I just want to pass the value of the Cost to a confirmation page & email which will be sent to the User. I am using formMail for processing the form. I have no problem sending all the other fields like the number of adult, child etc because the field name is processed, but when the ID values are getting processed, the value is not carried through to the email.

I have the menu options like this. Here the value of the SR_UNDER6 gets passed on to the autoresponds form. I am using SR2 for calcualtions in the script you provided…


<select name="SR_UNDER6" class="formselectwhite"  id="SR2">
                          <option>0</option>
                          <option>1</option>
                          <option>2</option>
                          <option>3</option>
                          <option>4</option>
                          <option>5</option>
                        </select>

… but here the GRNDTOTAL value does not get passed on to the next confirmation email.


<span id=GRNDTOTAL  type="text" readonly size=10 STYLE="width: auto;" />

So I created a hidden input field with name=GRNDTOTAL2 and added the following codes. The correct value is now displayed on the main form (hidden removed for debugging), but still does not get passed on to the confirmation page.


....
<input type="hidden" id="GRNDTOTAL2">
...
var display = document.getElementById("GRNDTOTAL2");
...
 // Update cost
   totalCost = totalCostFRadults;
   cost.innerHTML ='$' + totalCost + '.00';
   display.value = totalCost;

I hope I did not create any confusion. Thank you.

Hi,

That’s the correct way to go about it.
You would have something like this:

<form action="myscript.php" method="post">
  ... All of your form stuff ...
  <input type="hidden" name="total"  id="hiddenTotal">
  <input type="submit" value="Submit">
</form>

Then when your JavaScript has done its calculations, update both the <span> so as to give the user the visual feedback that everything is good and also update the hidden field, so that when the form is submitted you have access to the value you need in the $_POST array in your PHP script.

// Update cost
totalCost = totalAdults * 45;
cost.innerHTML = '$' + totalCost;
document.getElementById("hiddenTotal").value=totalCost;

Then in your PHP script:

$totalCost = $_POST('total');

Does that help?