0

I am working on a project where calculator functionality is needed and there should be support for adding more values through JavaScript and also print out the sum from all the numbers in the document.

The digits entered need to be two-digit numbers. Blank or non-numeric data should be skipped. Here is what I have so far:

<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <title>Sum Calculator</title>
</head>
<body>
Number of Rows: <input type= text value=2 style="width:30px" maxlength=2 >&nbsp;&nbsp;<input type=button value='Change' onclick="" />
<br /><br />
<table cellspacing=0 cellpadding=4>
<tr><td>Number 1:</td><td><input value=20 style="width:30px" type=text  maxlength=2/></td></tr>
<tr><td>Number 2:</td><td><input value=25 style="width:30px" type=text  maxlength=2/></td></tr>
<tr><td style="border-top:solid 1px black;border-bottom:solid 1px black;">Sum:</td><td style="border-top:solid 1px black;border-bottom:solid 1px black;"><div>45</div></td></tr>
</table>
<input type=button value='Recalculate Sum' onclick="" />
</body>
</html>

Any advice how I can add another row in the table with JavaScript and calculate the end result of all the fields in the table?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Laziale
  • 7,965
  • 46
  • 146
  • 262
  • Well first up you should be aware IE write-protects tables (`COL COLGROUP TABLE TBODY TFOOT THEAD TR`) so you'll find cross-browser inconsistency. Look for a JS library that deals with modifying part of a table. See: http://stackoverflow.com/questions/4729644/cant-innerhtml-on-tbody-in-ie – Rudu Jan 09 '12 at 17:51

1 Answers1

0

Quite easy actually. Do this:

  <table cellspacing=0 cellpadding=4>
     <tbody id="whateverId">
       <tr><td>Number 1:</td><td><input value=20 style="width:30px" type=text            maxlength=2/></td></tr>
       <tr><td>Number 2:</td><td><input value=25 style="width:30px" type=text  maxlength=2/></td></tr>
       <tr><td style="border-top:solid 1px black;border-bottom:solid 1px black;">Sum:</td><td style="border-top:solid 1px black;border-bottom:solid 1px black;"><div>45</div></td></tr>
     </tbody>
  </table>

The js for creating:

  var trEl = document.createElement('tr');
  trEl.setAttribute('attribute', 'value'); // replace that with what you need

  var tdEl = document.createElement('td');
  // Here set td attributes
  trEl.appendChild(tdEl);
  // And same for the input im to lasy to write.

  document.getElementById('whateverId').appendChild(trEl);

And... that's it. Group it in a function or whatever you want.

For the sum you just do something like:

  var s = 0;
  for (var i = 0; i < document.getElementById('whateverId').childNodes.length; i++)
  {
      s += document.getElementById(whateverId).childNodes[i].firstChild.firstChild.value; // Hope I counted the first childs right.... you get the point.
  }
zozo
  • 8,230
  • 19
  • 79
  • 134