• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1333
  • Last Modified:

Sum total of input fields, fields generated from PHP for loop

I'm building a deposit form for users to submit information.  It'll send info to the MySQL DB eventually, but right now I am working on getting the form functionality correct.  I'm having trouble figuring how to sum the fields to create a total field.

I created the fields to create an array for input to the DB, that is whats causing my question.

My Code is here.

// this is the deposit submit form

function createDepositForm() { ?>
	<form name="depositsubmit" action="" method="POST">
    <?php for ($i = 1; $i <= 10; $i++) { ?>
	<select name="pmntFrom[]" style="min-width:100px">
      <option selected="selected">Fund Source</option>
      <option value="1">Congregation Giving</option>
	  <option value="2">Outside Fundraising</option>
	  <option value="3">Denominational Support</option>
	  <option value="4">Event Registrations</option>
	  <option value="5">Reimbursements/Refunds</option>
	  <option value="6">Cafe/Book Sales</option>
	</select>
	<select name="desigAcct[]" style="width:100px"></select>
	<input type="textarea" name="memo[]"></input>
	<select name="currencyType[]" style="width:100px"></select>
	<input type="text" name="lineAmount[]" value="amount"></input><br/>
	<?php } ?>
    <input type="text" name="depositTotal">Total Deposit:</input><br/>
	<input name="submit" type="submit" value="Process Deposit">
	</form>
	<?php
} // end createDepositForm() //

Open in new window

0
axessJosh
Asked:
axessJosh
  • 3
  • 2
  • 2
1 Solution
 
HagayMandelCommented:
Is this what you're looking for?
function createDepositForm() {
$total = 0;
$line_subtotal = array();
if (isset( $_POST['submit'] )) { 
		for ($i = 1; $i <= 10; $i++) {
			if (isset($_POST['lineAmount_' . $i])) { 
			$line_subtotal[$i] = (int)$_POST['lineAmount_' . $i];
			$total = $total + (int)$_POST['lineAmount_' . $i];
		}
	}	
}	

echo '<form name="depositsubmit" action="" method="POST">';
for ($i = 1; $i <= 10; $i++) { 
	echo '<select name="pmntFrom_' . $i . '" style="min-width:100px">
		<option selected="selected">Fund Source</option>
		<option value="1">Congregation Giving</option>
		<option value="2">Outside Fundraising</option>
		<option value="3">Denominational Support</option>
		<option value="4">Event Registrations</option>
		<option value="5">Reimbursements/Refunds</option>
		<option value="6">Cafe/Book Sales</option>
		</select>
		<select name="desigAcct_' . $i . '" style="width:100px"></select>
		<input type="textarea" name="memo[]"></input>
		<select name="currencyType_' . $i . '" style="width:100px"></select>
		<input type="text" name="lineAmount_' . $i . '" value="amount" onfocus="this.value=\'\'"></input><br/>';		
	} 
	echo '<input type="text" name="depositTotal" value="' . ($total>0? $total:"") . '">Total Deposit:</input><br/>
	<input name="submit" type="submit" value="Process Deposit">
	</form>';
}

Open in new window

0
 
axessJoshAuthor Commented:
Yea, that would work, but I'd like the totals to be added using JS as they are entered.  Some sort of onChange event.

I've found several pieces of code that'll do it, however none of them work with the way I have it setup because of the While loop.
0
 
HagayMandelCommented:
Next time, do a specific request for a JS bases solution!

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>The document title</title>
  <meta name="description" content="">
	<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<?php
// this is the deposit submit form
createDepositForm(); 
function createDepositForm() {
/* $total = 0;
$line_subtotal = array();
if (isset( $_POST['submit'] )) { 
		for ($i = 1; $i <= 10; $i++) {
			if (isset($_POST['lineAmount_' . $i])) { 
			$line_subtotal[$i] = (int)$_POST['lineAmount_' . $i];
			$total = $total + (int)$_POST['lineAmount_' . $i];
		}
	}	
} */

echo '<form name="depositsubmit" action="" method="POST">';
for ($i = 1; $i <= 10; $i++) { 
	echo '<select name="pmntFrom_' . $i . '" style="min-width:100px">
		<option selected="selected">Fund Source</option>
		<option value="1">Congregation Giving</option>
		<option value="2">Outside Fundraising</option>
		<option value="3">Denominational Support</option>
		<option value="4">Event Registrations</option>
		<option value="5">Reimbursements/Refunds</option>
		<option value="6">Cafe/Book Sales</option>
		</select>
		<select name="desigAcct_' . $i . '" style="width:100px"></select>
		<input type="textarea" name="memo[]"></input>
		<select name="currencyType_' . $i . '" style="width:100px"></select>
		<input type="text" name="lineAmount_' . $i . '" class = "sub_total" value="amount"></input><br/>';		
	} 
	echo '<input type="text" name="depositTotal" id="depositTotal">Total Deposit:</input><br/>
	<input name="submit" type="submit" value="Process Deposit">
	</form>';
}
?>


</script>
  <script type="text/javascript">
		$(document).ready(function() { 		
		var oldValue=0;
		var sum = 0;
			$('.sub_total').on('keyup', function (e) {
				var prev=0;
				if (e.keyCode >= 48 && e.keyCode <=57) {
					var len = $(this).val().length;
					if (len>1){
					var oldValue = $(this).val().slice(0,$(this).val().length-1);					
						sum = sum - parseInt(oldValue);
						sum += parseInt($(this).val());
					} else {
						sum += parseInt($(this).val());
					}																			
					$('#depositTotal').val(sum);					
				}
			});
		});
	</script>
</body>
</html>

Open in new window

0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
axessJoshAuthor Commented:
thanks, I put it into both the PHP and JS categories since we had both there and i wasn't quite sure how one affected the other.

Seems to be working fine, however, i noticed a bug that if the value gets inputted, then deleted, the sum doesn't update to reflect the change.
0
 
Slick812Commented:
maybe you can use this or not ? but you have some incorrect FORM code for TEXT inputs (in my view) and you do not say how , when to tally up the total, I have had some trouble will users being confused by onblur and onchange events in text inputs, I have added a BUTTON so there is no confusion, click button to add up amounts.

   php code below
<?php function createDepositForm() { ?>
	<form name="depositsubmit" action="" method="POST">
    <?php for ($i = 1; $i <= 7; $i++) { ?>
	<select name="pmntFrom[]" style="min-width:100px">
      <option selected="selected">Fund Source</option>
      <option value="1">Congregation Giving</option>
	  <option value="2">Outside Fundraising</option>
	  <option value="3">Denominational Support</option>
	  <option value="4">Event Registrations</option>
	  <option value="5">Reimbursements/Refunds</option>
	  <option value="6">Cafe/Book Sales</option>
	</select>
	<select name="desigAcct[]" style="width:100px">
	<option selected="selected">Top Acc</option>
	</select>
	<input type="textarea" name="memo[]" />
	<select name="currencyType[]" style="width:100px">
	<option selected="selected">US</option>
	<option>euro</option>
	</select>
	<input type="text" name="lineAmount[]" value="12" /><br/>
	<?php } ?>
    <input type="text" name="depositTotal" />Total Deposit: - <input type="button" value=" Add Amounts "  onclick="addAmounts();"/><br/>
	<input name="submit" type="submit" value="Process Deposit" />
	</form>
	<?php
} // end createDepositForm()
createDepositForm();
?>

Open in new window


  javascript below
<script>
function addAmounts(){
var eleLen = document.depositsubmit.elements.length;
var amtTotal = 0;
for (var i=4; i < eleLen; i+=5) {
    amtTotal += (document.depositsubmit.elements[i].value*1);
    }
document.depositsubmit.elements[eleLen-3].value = ""+amtTotal;
}
</script>

Open in new window


This is not a fully tested code, but does work as far as I have tried it.
ask questions if you need more info
0
 
axessJoshAuthor Commented:
hey Slick812, i tried this but get a NaN return as the value of the button.  suggestions?
0
 
Slick812Commented:
OK, but you did NOT say anything about text value field "Validation" My code works if you have the amount fields (form elements) with a number string, here is some code that also does a simple Validation, but you may need to see if the amounts are below or above certain amounts, also I have on purpose  NOT used any element identify by name= as an Number sufix, which will Invalidate your array access in the PHP

This will do an js alert for amounts that are blank or a non number, but I only tested in firefox. No change in the PHP code
<script>
function addAmounts(){
var eleLen = document.depositsubmit.elements.length;
var amtTotal = 0;
var num = 0;
for (var i=4; i < eleLen; i+=5) {
    if (document.depositsubmit.elements[i].value.length > 0) {
	    num = (document.depositsubmit.elements[i].value*1);
	    if (isNaN(num)) {
                document.depositsubmit.elements[i].focus();
                alert("ERROR - the Amount in row "+((i+1) / 5)+" is NOT a number, please re-enter amount");
                return;
                }
        amtTotal += num;
        } else {
        document.depositsubmit.elements[i].focus();
        alert("ERROR - the Amount in row "+((i+1) / 5)+" is Blank, please place Number there.");
        return;
        }
    }
document.depositsubmit.elements[eleLen-3].value = ""+amtTotal;
}
</script>

Open in new window


I hope it helps, but you will likely need to adjust the element array number I use as "var i" in the for loop, , if you add or remove elements to your form.
0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

  • 3
  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now