How would I write this sum in Javascript

Posted on 2014-03-05
Last Modified: 2014-03-05
I've got a dynamic list that grows or diminishes based on the number of rows a user adds. It looks like this:

<input type='text' size='10'  class='text' name='allocated_".$i."' value='".$allocatedlist[$i]["totalcost"]."'

I want to install a JavaScript function that adds all the values in the "allocate_$i" field. How would I do that?
Question by:brucegust
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 3
LVL 33

Expert Comment

by:Big Monty
ID: 39907001
for a pure javascript perspective (although this would be much easier to do in jQuery), you can do something like:

function addAllocated() {
var theForm = document.form;
var numRows = document.getElementById("tableID").rows.length;

for( var rowIndex = 0; rowIndex < numRows; rowIndex++ ) 
    total += document.getElementsByName("allocated_" + rowIndex).value;


Open in new window

this asusmes your table has one text box for every row, if that's not the case, you'll need to tweak the script to account for that

Author Comment

ID: 39907136
Big M!

Poised on the threshold of greatness, I know it!

Here's what I coded based on your counsel:

function addAllocated(countRows) {
var theForm = document.form;
var numRows = countRows
for( var rowIndex = 0; rowIndex < numRows; rowIndex++ )
    total += document.getElementById('allocated_' + rowIndex).value;
    return total;

When I do an "alert(countRows)," just to makes sure my function is seeing what I hope it's seeing, I'm getting the correct number, so we're golden there.

Here's the way I'm calling my function:

<script type='text/javascript'>var allocated_total = addAllocated(".$allocatedlist["count"].")</script>

I'm not getting any kind of number.

So, what I am doing wrong and do you need more of my page to get a better picture of where I might be falling short?
LVL 33

Accepted Solution

Big Monty earned 500 total points
ID: 39907162
this line

<script type='text/javascript'>var allocated_total = addAllocated(".$allocatedlist["count"].")</script>

is just creating a variableallocated_total, you're not displaying it anywhere (that I can see). you're also passing in a variable that is a string (as defined by the quotes surrounding it. no need to pass in a parameter, unless you want to apply this to multiple tables? If so, you should do it this way:

function addAllocated( tableID ) {
var numRows = document.getElementById( tableID ).rows.length;

for( var rowIndex = 0; rowIndex < numRows; rowIndex++ ) 
    total += document.getElementsByName("allocated_" + rowIndex).value;


return false;   //-- prevents scrolling

Open in new window

then, at the bottom of your page, you can see if it's working by doing this:
<script type='text/javascript'>var allocated_total = addAllocated("myTableID"); alert( allocated_total );</script>

Open in new window

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!


Author Comment

ID: 39907201

Check this out, though...

Every function on the page that I'm currently working on has used a convention where they're passing a variable from PHP to JavaScript using something like this:

eval('comparison = form.total_cost_comparison_'+row+'.value;');
eval('user_value = form.allocated_'+row+'.value;');

Open in new window

In other words, before there's any attempt to deploy a JavaScript functionality, the variables in question do a hand off from PHP to something that JavaScript can work with.

That said, when I do this:

alert("allocated_" + rowIndex);

I get "allocated_undefined." Do I need to do something similar to the "eval" dynamic I've got above and, if so, how would you incorporate that into your loop?
LVL 33

Expert Comment

by:Big Monty
ID: 39907344
the function I gave you doesn't require any parameters, except for the ID of the table you want calculated. It takes the number of rows from that table and loops through each row in the for-loop, where it keeps a running tab of the allocated text boxes. Once the loop finishes, it returns the value through the function, so wherever you are going to use that number, you just call the function. As an example, I just put that value in a alert box.

I guess I'm not clear on what you want to do with that total once you have it.

Author Comment

ID: 39907435
Fret not, sir! I got some additional input from someone in my shop and between you and them, we got it to sing!

LVL 75

Expert Comment

by:Michel Plungjan
ID: 39908549
Please remember to parse form values before adding!
parseInt(value,10) or parseFloat(value)

Featured Post

Salesforce Made Easy to Use

On-screen guidance at the moment of need enables you & your employees to focus on the core, you can now boost your adoption rates swiftly and simply with one easy tool.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Question regarding to $.ajax() with type "POST" vs $.post() 4 32
Use Mid in Html 6 23
Echo'd values in dropdowns 6 32
How do I split a variable to newline 2 20
Article by: DanRollins
This article describes a JavaScript program that creates a maze made of hexagonal cells.  In Part 2 (, we'll extend the program by adding a depth-…
This article demonstrates how to create a simple responsive confirmation dialog with Ok and Cancel buttons using HTML, CSS, jQuery and Promises
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

730 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question