[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

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

Javascript simple addition calculator

The below code would be exactly what I need if I could just

get the values to automatically calculate without an event handler
get the values and total to output as text instead of in input boxes
and lastly if the calculater could add decimals instead of rounding up


It would be awesome if someone could help me with this.
<html>
<head>
<script language="javascript">
function addAll(){
var frm = document.f;
var total = 0;
for (var i=0;i<frm.num.length;i++){
total+=parseInt(frm.num[i].value);
}
frm.tot.value=total;
}
</script>
</head>
<body>
<form name="f">
<input type="text" name="num" value="00.00" onclick="addAll()">
<input type="text" name="num" value="00.00" onclick="addAll()">
<input type="text" name="num" value="00.00" onclick="addAll()">
<input type="text" name="num" value="00.00" onclick="addAll()">
<input  name="tot" value="00.00" onfocus="this.click()" readonly>
</form>
</body>
</html>

Open in new window

0
turtleman2009
Asked:
turtleman2009
  • 7
  • 7
1 Solution
 
HonorGodCommented:
Something like this perhaps?
<html>
<head>
<script type='text/javascript'>
  function addAll(){
    var row = document.getElementById( 'row1' )
    if ( row && ( row.nodeName == 'TR' ) ) {
      var last = null
      var total = 0.0
      for ( c = 0; c < row.childNodes.length; c++ ) {
        var cell = row.childNodes[ c ]
        if ( cell && cell.nodeName == 'TD' ) {
          last = cell
          var child = cell.firstChild
          if ( child && child.nodeName == '#text' ) {
            total += parseFloat( child.nodeValue );
          }
        }
      }
      if ( last ) {
        var td = document.createElement( 'TD' )
        var text = document.createTextNode( total.toFixed( 2 ) )
//      alert( total.toFixed( 2 ) )
        row.appendChild( td )
        td.appendChild( text )
      }
    }
  }
</script>
</head>
<body onload='addAll()'>
  <form name="f">
    <table border='1'>
      <tr id='row1'>
        <td>1.01</td>
        <td>2.02</td>
        <td>3.03</td>
        <td>4.04</td>
        <td>5.05</td>
      </tr>
    </table>
  </form>
</body>
</html>

Open in new window

0
 
turtleman2009Author Commented:
Thank you so much. That has the functionality of what I need but my limited understanding keeps me from making necessary alterations. I have posted below how the values need to be. They will be in divs and I need to have code so I can put the total text where I need it
<div class="gift" align="center">00.00</div>
<div class="gift" align="center">00.00</div>
<div class="total" align="center">00.00</div>

Open in new window

0
 
HonorGodCommented:
Ah, I didn't know what kind of input structure you were using, so I just used a table.

If you are going to be using a div for each entry, that should only take a little effort to change...

One moment please... :-)

0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
HonorGodCommented:
Something like this perhaps?
<html>
<head>
<script type='text/javascript'>
  //--------------------------------------------------------------------
  //  Name: getElementsByClass()
  //  Role: Provide very useful getElementByClass functionality
  //  From: http://www.dustindiaz.com/getelementsbyclass
  // Parms: searchClass == className to be matched   [Required]
  //        node        == Starting point for search [Optional]
  //        tag         == tag names to be searched  [Optional]
  //--------------------------------------------------------------------
  function getElementsByClass( searchClass, node, tag ) {
    var classElements = new Array();
    if ( node == null )
      node = document;
    if ( tag  == null )
      tag = '*';
    var els = node.getElementsByTagName( tag );
    var elsLen = els.length;
    var pattern = new RegExp( "(^|\\s)"+searchClass+"(\\s|$)" );
    for ( var i = 0, j = 0; i < elsLen; ++i ) {
      if ( pattern.test( els[ i ].className ) ) {
        classElements[ j ] = els[ i ];
        j++;
      }
    }
    return classElements;
  }
 
  function addAll(){
    var gifts = getElementsByClass( 'gift' )
    if ( gifts ) {
      var total = getElementsByClass( 'total' )[ 0 ]
      var sum = 0.0
      if ( total ) {
        for ( var g = 0; g < gifts.length; g++ ) {
          var child = gifts[ g ].firstChild
          if ( child && child.nodeName == '#text' ) {
            sum += parseFloat( child.nodeValue )
          }
        }
        child = total.firstChild
        if ( child && child.nodeName == '#text' ) {
          child.nodeValue = sum.toFixed( 2 )
        } else {
          total.appendChild( document.createTextNode( sum.toFixed( 2 ) ) )
        }
      } else {
        alert( 'No elements with class="total" found.' )
      }
    } else {
      alert( 'No elements with class="gift" found.' )
    }
  }
</script>
</head>
<body onload='addAll()'>
  <div class='gift'>11.11</div>
  <div class='gift'>22.22</div>
  <div class='gift'>33.33</div>
  <div class='gift'>44.44</div>
  <div class='gift'>55.55</div>
  <div class='total'></div>
</body>
</html>

Open in new window

0
 
turtleman2009Author Commented:
Thank you so much. This is exactly what I have been looking for. It works perfect!
0
 
HonorGodCommented:
That is excellent news.  Thanks for the grade & the points.

Good luck & have a great day.
0
 
turtleman2009Author Commented:
I am really sorry I thought I was done but there is one more thing I need.

I have need to change the class on different pages so it will only pull certain years from the database. So I tried to change the class to gift2009. but it gave me a total of NaN. Is their something else I should be doing to change the class.
var gifts = getElementsByClass( 'gift2009' )

Open in new window

0
 
HonorGodCommented:
What does the HTML containing this class look like?
0
 
turtleman2009Author Commented:
So it all works when i want to add all years of gifts together but when I want to just ad up one years worth of giving is where it gets crazy:

The <tmpl_var gift_date> produces the date of the gift like 01/01/2009 so I am having to take away the first 6 characters and then add the word gift to the front of it. This way it will only add all of the gift2009's instead of all of the years which are driven from the database all at the same time from a loop.


p.s. the <tmpl_var gift_amount> produces the amount of the gift.

Once again Thanks!
<script type="text/javascript"> 
var str ="<tmpl_var gift_date>"; 
var newStr = str.substring(6);
var newCStr = str.substring(6);
var div = 'gift' + newStr;
var cls = 'gift' + newCStr;
 
document.write("<div id=\"" + div + "\" class=\"" + cls + "\" >");
</script>
	    <tmpl_var name="gift_amount">
	 
	</div>

Open in new window

0
 
HonorGodCommented:
ooh... That's XML, not HTML.

and the "generated code" is invalid.

--------------------------------------------------
var str ="<tmpl_var gift_date>";
var newStr = str.substring(6);
var newCStr = str.substring(6);
--------------------------------------------------

Do you know what the values of newStr and newCStr are?

"var gift_date>"

I'm quite certain that you don't want to generate a line like this:

<div id="var gift_date>" class="var gift_date>" >

Open in new window

0
 
HonorGodCommented:
This is a bit off the original question.  How about opening a related question?
0
 
turtleman2009Author Commented:
I am not sure. that is just code that I copied. the only reason I have that code there is to try to get the outputted data like: 01/01/2009 converted to gift2009 so I can use it as a class so it can add the values up

0
 
turtleman2009Author Commented:
yeah way off original question, I am opening a new one
0
 
turtleman2009Author Commented:
0

Featured Post

New feature and membership benefit!

New feature! Upgrade and increase expert visibility of your issues with Priority Questions.

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