Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

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

Posted on 2013-01-23
7
Medium Priority
?
1,266 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
[X]
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
  • 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
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
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 2000 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: 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

Boost your ability to deliver ambitious and competitive web apps by choosing the right JavaScript framework to best suit your project’s needs.
There are times when I have encountered the need to decompress a response from a PHP request. This is how it's done, but you must have control of the request and you can set the Accept-Encoding header.
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.
Suggested Courses

618 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