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
Solved

How would I write this sum in Javascript

Posted on 2014-03-05
7
192 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 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
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 33

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
Free Tool: Postgres Monitoring System

A PHP and Perl based system to collect and display usage statistics from PostgreSQL databases.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 

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

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
search bar text disappears when click/touch on page content (framework7 phonegap) 1 36
asp.net mvc5 6 20
Javascript the "if condition with Or" 8 29
multiple selects 23 48
This article will give core knowledge of JavaScript and will head in to your first JavaScript program. I am Durvesh Naik and I am here to deal with this series of JavaScript. I will teach you JavaScript in part wise , as its quite boring to read big…
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…

809 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