Most examples on the Internet regarding automatically adding together the values of a form and then displaying the result usually involve forms that are made up of two, three input boxes. So, what if you’re looking to do this on a dynamically generated form, perhaps generated with information extracted from a database, and you don’t know from the beginning how many input boxes you have?
My solution was to dynamically generate both the HTML form and the JavaScript code, both using PHP.
To illustrate this I'll use a simple financial calculator example. Note that I'll only present the actual code that does all the adding and code-generating, without any attempts to verify the user's input (for example if he enters letters instead of numbers) as this would be beyond the purpose of this post.
Let’s assume we have a database of fund names in which the user has invested some money. We want to create a form that allows the user to specify how much money is currently invested into each fund, while also displaying the total amount of money invested.
For simplicity we’ll consider that the fund names ($N of them) have already been extracted from the database and are stored in an array called $funds. In our example I'll simply declare these at the start:
<?php$N=5;
$funds[1]="RoOilingInc";
$funds[2]="BakingRUs";
$funds[3]="ManchesterUnited";
$funds[4]="Microsoft";
$funds[5]="Apple";
Moving on, it's time to create the JavaScript code that will sum up the form.
echo "<script type='text/javascript' language='JavaScript'>
function usum() {
var a = 0;
var b = 0;
var c = 0;
";
For ($i=1;$i<=$N;$i++)
{
echo " c = document.myform.".$funds[$i].".value;
c += '';
b = (a * 1) + (c * 1);
a = b*1; ";
}
echo "document.myform.sum.value = parseInt(a); }
</script>";
Now, for the final section of code, the generation of the HTML form. First we need to declare the form and create the input boxes:
echo "<FORM NAME='myform'>";
for ($i=1;$i<=$N;$i++)
{
echo $funds[$i]."$<INPUT TYPE='text' NAME='".$funds[$i]."' ID='".$funds[$i]."' onChange='usum();'>
";
}
echo "TOTAL VALUE$ <INPUT TYPE='text' STYLE='color: #00cc00; background: #ffffff; border: solid 0px #000000;' NAME='sum' DISABLED VALUE='0' ID='sum'></FORM>";
?>
Alright, we're finished. Run the .php file (don't forget to upload it to a website or use an Apache server) and you should see the 5 input boxes. Once you write a number in one of them it should be added to the Total Value display.
Hope this helps.
discuss this topic to forum
