Link to home
Start Free TrialLog in
Avatar of stkoontz
stkoontzFlag for United States of America

asked on

Looop through JQuery by concatenating variables

I'm using JQuery to automatically add up fields as the user inputs numbers.  It works fine with a set number of fields.  But the application will get the fields from a database, so the number of fields will vary each time.

It's very rough, but here's the page...
http://buildmomentum.org/register/lc/group_payment.php?id_church=ORG101

The fields are created by looping through the database.

You'll see that the first 4 fields work, but the remaining don't.

I'm trying to convert some JQuery code so that it loops to create the variables.

I've managed to insert the variable 'x' into the parseFloat statement so I can get that to change each loop -   parseFloat($('#id_amount'+x)

But how do I get - var firstValue - to change?  I've tried every way I can think of...

var first + x
var first[x]
var first$x
etc.

Any ideas or should I apply a different logic to the problem?
<code>
<script>
$(document).ready(function(){
$('input').keyup(function(){ // run anytime the value changes
x=1

for (var x = 0, limit = 2; x < limit; x++) {
console.log( "Currently at " + x );

var firstValue = parseFloat($('#id_amount'+x).val()) || 0; // get value of field

<!--these are hardcoded for now, but need to be in the loop-->
var secondValue = parseFloat($('#id_amount2').val()) || 0; // convert it to a float
var thirdValue = parseFloat($('#id_amount3').val()) || 0;
var fourthValue = parseFloat($('#id_amount4').val()) || 0;
    
<!--this needs to loop as well since the number of records will vary-->
var total = firstValue + secondValue + thirdValue + fourthValue; // add them together

$('#added').html(total); // output it
}
});
});
</script>
</code>

Open in new window

Avatar of Tom Beck
Tom Beck
Flag of United States of America image

My understanding is that you are trying to get the values entered in a series of inputs and add them together. Something like this perhaps?

var total = 0;
$("input[name^='amount_entered']").each(function(i) {
     total += parseFloat($(this).val());
});

Or this:

var total = 0;
$("input[id^='id_amount']").each(function(i) {
     total += parseFloat($(this).val());
});
Avatar of stkoontz

ASKER

Thanks for jumping it to help.  I appreciate it.

I'm new to jquery and haven't done much in Javascript either.  Would you let me know how this code would fit with my code?  What would it replace?

Thanks,

Steve
$(document).ready(function(){
$('input').keyup(function(){ // run anytime the value changes

    var total = 0;
    $("input[id^='id_amount']").each(function(i) {
          total += parseFloat($(this).val());
    });

    $('#added').html(total); // output it
});
});

Open in new window

Of course, you would probably want to test for empty inputs and non-numerical inputs before attempting to add the values.

var total = 0;
    $("input[id^='id_amount']").each(function(i) {
            if ($(this).val() !== "" && !(isNaN($(this).val()))) {
                      total += parseFloat($(this).val());
            }
    });
Just change your input's to a class.  No need for id's in this case.  Instead, just target a class which can be the same name.  See this simplified sample.
http://jsbin.com/OLiGEcA/1/edit?html,js,output
var total=0;
$('input.amount').each(function(){
  var amt=0;
  if ($(this).val()>0){
   amt=$(this).val();
  }
   total=total+parseInt(amt,10);
});
$('td.total').text(total);

Open in new window


<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
<table>
  <tr><td><input class="amount" ></td><td>abc</td></tr>
  <tr><td><input class="amount"></td><td>123</td></tr>
  <tr><td><input class="amount" ></td><td>xyz</td></tr>
  <tr><td class="total"></td><td>total</td></tr>
  </table>  
</body>
</html>

Open in new window

For jquery,  use either 1.1x or 2.x.  The 1.1x will support older IE where the 2.x does not and is lighter weight.  If you are not sure, use the 1.1x.
Thanks for both of you trying to help, but neither solution worked.

If I can put a variable that increments in place of [variable] below, I could get it to work.

var Value[variable] = parseFloat($('#id_amount'+i).val()) || 0;

Is that possible?

Steve
When you say neither solution worked, can you elaborate? Can you post your latest code that attempts to implement the solutions provided?

If the inputs are being dynamically generated with incrementing ids, then it has to work.
I realized my code will not work as is.   It needs to be wrapped in a blur or click function of some sort.  

But I am confused looking at your sample.  http://buildmomentum.org/register/lc/group_payment.php?id_church=ORG101

Do you mean for the amounts to be input fields or do you want to add up the leftmost td's?
You are trying to load jQuery version 1.1 from the Google CDN - the oldest version they have is 1.2.3, so you're getting a 404 error and jQuery is never loaded. Change your code to include a newer library:

<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>

Open in new window

This question has gotten messy. The code I provided in post ID: 39713948 was a working solution except that there was no test for blank inputs or non-numerical inputs. I added that in post ID: 39713974. But I see now from the link that the onkeyup wrapper in the 39713948 code got lost somehow. That plus loading the wrong jQuery library are the reasons the page does not work.

When I answered the question originally, I copied the entire view source from the link and created a local copy. I still have it. It included this jQuery library: <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>. How it went from 1.7.0 to 1.1.0 is a mystery to me, but that prompted Chris's input. I never suggested a change to the library version. I also did not suggest a change in the markup from using ids to using classes. That was @padas.

So please @stkoontz, how would you like to proceed here? Do you want to:
1.) change your markup to include classes in the inputs instead of ids?
2.) add the onkeyup wrapper back in and keep the ids and my code suggestion?
3.) continue to insist on trying to concatenate id_amount with a variable?
ASKER CERTIFIED SOLUTION
Avatar of Tom Beck
Tom Beck
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I might be in over my head here until I learn more javascript.  I'll answer padas' question first, then look through the code to try to answer TommyBoy's.

Pada's question..

"Do you mean for the amounts to be input fields or do you want to add up the leftmost id's?"

I want the amounts to be input fields.  Here's a link to a cleaned up page, but still with original code.  (I won't change this page as I test code.)

http://buildmomentum.org/register/lc/group_paymentjquery.php?id_church=ORG101

When the user enters a number in the Amount Paid column, it should add up and be displayed next to "Total Paid."  This works for the first 5 names because it's hard-coded.  I need the loop so it can be used on a varying number of names.

Now I'll take a look at TommyBoy's last uploaded code.

Steve
@tommyboy:  I dropped in my PHP code to pull the information from the database, keeping your jquery in tact and it's working great.  I'm going to test it some more so I understand what's going on before I close the question.

Thanks!

Steve
It's working great, but I can't figure this out...

    $("input[id^='id_amount']").each(function(i) {

How is this line converted to id_amount1, id_amount2, etc so that the amounts are associated with the correct name?  Or maybe I'm just not understanding the logic.

Thanks,

Steve
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
@tommyBoy - thanks for solving the problem with the example code.

@padas - thanks for the extended explanation and HTML tips.  I tweaked the code and ran the validator and the code clears now.
The author asked me for an explanation of this line of code:

$("input[id^='id_amount']").each(function(i) {

I posted an explanation and you removed it. Clear enough?