Solved

How would I write this sum in Javascript

Posted on 2014-03-05
7
188 Views
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:

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

I want to install a JavaScript function that adds all the values in the "allocate_$i" field. How would I do that?
0
Comment
Question by:brucegust
  • 3
  • 3
7 Comments
 
LVL 32

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
0
 

Author Comment

by:brucegust
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?
0
 
LVL 32

Accepted Solution

by:
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

0
Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

 

Author Comment

by:brucegust
ID: 39907201
Progress!

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?
0
 
LVL 32

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.
0
 

Author Comment

by:brucegust
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!

Thanks!
0
 
LVL 75

Expert Comment

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

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Suggested Solutions

Introduction HTML checkboxes provide the perfect way for a web developer to receive client input when the client's options might be none, one or many.  But the PHP code for processing the checkboxes can be confusing at first.  What if a checkbox is…
Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
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…

758 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

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now