Solved

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

Posted on 2013-01-23
7
939 Views
Last Modified: 2013-06-18
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
Comment
Question by:axessJosh
  • 3
  • 2
  • 2
7 Comments
 
LVL 16

Expert Comment

by:HagayMandel
ID: 38813242
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
 
LVL 2

Author Comment

by:axessJosh
ID: 38814450
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
 
LVL 16

Expert Comment

by:HagayMandel
ID: 38814970
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
Gigs: Get Your Project Delivered by an Expert

Select from freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely and get projects done right.

 
LVL 2

Author Comment

by:axessJosh
ID: 38815011
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
 
LVL 33

Expert Comment

by:Slick812
ID: 38815187
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
 
LVL 2

Author Comment

by:axessJosh
ID: 38815209
hey Slick812, i tried this but get a NaN return as the value of the button.  suggestions?
0
 
LVL 33

Accepted Solution

by:
Slick812 earned 500 total points
ID: 38815557
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

Gigs: Get Your Project Delivered by an Expert

Select from freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely and get projects done right.

Question has a verified solution.

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

Suggested Solutions

International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
Password hashing is better than message digests or encryption, and you should be using it instead of message digests or encryption.  Find out why and how in this article, which supplements the original article on PHP Client Registration, Login, Logo…
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
The viewer will learn how to count occurrences of each item in an array.

776 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