Solved

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

Posted on 2013-01-23
7
1,018 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
Networking for the Cloud Era

Join Microsoft and Riverbed for a discussion and demonstration of enhancements to SteelConnect:
-One-click orchestration and cloud connectivity in Azure environments
-Tight integration of SD-WAN and WAN optimization capabilities
-Scalability and resiliency equal to a data center

 
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 34

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 34

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

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

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
document.write() deleting all existing HTML 5 51
Wordpress Cron - Send XML Data to external server FTP 3 23
PHP Mail error 3 27
Review of the nodejs code 1 16
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…
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…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
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…

860 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