# Text Box array?



## SerialChick (Aug 9, 2008)

Hi,

I'm creating a kind of form/calculator thing where people enter values into text boxes.

I want to make an array of text boxes so the site looks a little like:

txtOne[0] * txtTwo[0] = lblAns[0]
txtOne[1] * txtTwo[1] = lblAns[1]
txtOne[2] * txtTwo[2] = lblAns[2]

each textbox would have an onChange = func([array number])

and then I wanted to use JavaScript like

function func(num) {
value1 = document.form1.txtOne[num].value
value2 = document.form1.txtTwo[num].value
answer = value1 * value2
document.form1.lblAns[num].value = answer
}

I want to design it so there can be lots of sets of boxes, but when the user changes the value of one box it only updates that set. It would also save a lot of typing and would make it easier to add and delete sets.

Is this or something like it possible?

Thanks


----------



## jamiemac2005 (Jul 5, 2007)

Hey, i was having trouble working out how i'd do this effectively... and then how to explain it to you over the forum.

So i went ahead and created the basic calculator you describe(with the add/remove sets features)...

I've fully commented it so you can understand what's going on within the script

I used a table within a form because it is generally easier to add/remove rows etc.

I could go on telling you how i did it but i've attached the file and it will be easier to see from it how it works... Please post back if you have any queries about the script/page.

Cheers,
Jamey

p.s. i had to zip the file because the forum does not allow html files to be uploaded.


----------



## jamiemac2005 (Jul 5, 2007)

lol: p.s. it is possible =]


----------



## SerialChick (Aug 9, 2008)

thanks jamiemac2005!

you are so awesome!

i shall sing your praises until my dying day etc.

What i really needed was to find a way of having a variable in an element name, and you answered that by using document.getElementById("name" + variable).

So thank you again, and your program rocks.


----------



## SerialChick (Aug 9, 2008)

grr,

this isn't working.
what I'm doing is creating a form so, for example, say a teacher is organizing a school camp, and the form is something like:

*20* girls at *$200* = _$4000_
*10* boys at *$150* = _$1500_
total cost = _$5500_

so the script is:
Num1 * Cost1 = Ans1
Num2 * Cost2 = Ans2
Total = Ans1 * Ans2

the form is designed so that if you change the number or the cost for one set, then that Ans and the Total will change:

id="txtNum1" onchange= Cal(1)
id="txtCost1" onchange= Cal(1)

id="txtNum2" onchange= Cal(2)
id="txtCost2" onchange= Cal(2)

function Cal(idnum) {
Num = document.getElementById("txtNum" + idnum).value
Cost = document.getElementById("txtCost" + idnum).value
Ans = Num * Cost
document.getElementById("lblAns" + idnum).value = Ans

i can't get the id variable working plus i have no idea how to get the Total to work.

I want to design the form this way because in the end there will be lots of sets (this is just the basic example) and i want to design it so it is fairly easy to add a set, say if you suddenly want to take into account the extra cost for vegetarians.

what Jamiemac2005 did was helpful, but for some reason, when i translate it across, it doesn't work.

any ideas what i'm doing wrong?


----------



## SerialChick (Aug 9, 2008)

i figured it would help if I wrote out the code in full for what I had done in the example.
this code has the answer in a textbox, but in the final version I want it to be in a label.


```
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Basic Form</title>

<!-- SCRIPTING STARTS HERE!!! -->

<script language="javascript">
<!-- This is the function i use -->
function Cal(idnum) {
var NumBox = document.getElementById("txtNum" + num); //Set the variable name for the textbox value
var CostBox = document.getElementById("txtCost" + num);
var AnsBox = document.getElementById("txtAns" + num);

var Num = parseInt(NumBox.value); //Make sure the value is seen as a number, not a string
var Cost = parseInt(CostBox.value;
var Ans = Num*Cost;

AnsBox.value = Ans; //Display the answer
}
</script>
<!-- END SCRIPTING SECTION -->
</head>

<body>
<form id="form1" name="form1" method="post" action="">

<!-- SET ONE -->
  <p>
    <input type="text" name="txtNum0" id="txtNum0" value="0" onchange= Cal(0) /> //NumBox
    <input type="text" name="txtCost0" id="txtCost0" value="0" onchange= Cal(0)/> //CostBox
    <input type="text" name="txtAns0" id="txtAns0" readonly="true"/> //AnsBox
  </p>

<!-- SET TWO -->
  <p>
    <input type="text" name="txtNum1" id="txtNum1" value="0" onchange= Cal(1) />
    <input type="text" name="txtCost1" id="txtCost1" value="0" onchange= Cal(1)/>
    <input type="text" name="txtAns1" id="txtAns1" readonly="true"/>
  </p>
  
</form>
</body>
</html>
```


----------



## jamiemac2005 (Jul 5, 2007)

Hey, there weren't too many problems with your code:

1) the event handler:

```
onchange= Cal(0)
```
needs to be wrapped in quotes or double quotes:

```
onchange=[b]"[/b]Cal(1)[b]"[/b]
```
2) You had missed the end bracket ")" in the following snippet:

```
var Cost = parseInt(CostBox.value[b])[/b];
```
3) You used "num" within the document.getElementById(id) methods when num was neither a variable or a paramater(but "idnum" was):

```
var AnsBox = document.getElementById("txtAns" + [b]idnum[/b]);
```
(This was the same for NumBox, CostBox and AnsBox)...

Thats all, and it was just slight errors nothing major.

If you're not using Firefox as a testing browser i suggest you switch to it. And if you are then use the error console to see what's going wrong within your scripts (Tools->Error Console, click clear, load your page and see if it brings up errors, then use your page and see if it brings up errors)...

Cheers,
Jamey


----------



## SerialChick (Aug 9, 2008)

Thanks Jamey,

you've proven your awesomeness once again.
it works now. 
I don't suppose you have any ideas on how to do the total?

I was thinking of making an array for the ans then using a for statement to add them, however, i don't know how to say, when you reach the end of the sets, stop.
if it was something like:


```
total = 0
for (counter = 0; ??counter = Array.Length??; counter = counter + 1) {
       value = document.getElementById("lblAns" + counter);
       ans = parsFloat(value.value);
       total = total + ans;
}
```
but i have no idea what to use for the condition.

i also thought i might use a while statement.


```
total = 0
counter = 0
while (value != null) {
       ?if (document.getElement ById("lblAns" + counter) does not exist) {
                value = null;
                break;
        }
        else {
                value = document.getElement ById("lblAns" + counter);
                ans = parseFloat(value.value);
                total = total + ans;
        }
}
```
but once again, I have no idea how to say that.


----------



## jamiemac2005 (Jul 5, 2007)

Hey again,
i'm assuming you're using code close to that of what i looked at earlier...
i recon the way to do it is something like this:

```
//reference the form
var theForm = document.getElementById("form1");
//get a list of all the sets(this is how you determine when to stop
var pElements = theForm.getElementsByTagName("p");
//get an array of the values:
var seperateTotals = new Array();
for (var i = 0; i<pElements.length; i++){
    seperateTotals[i] = document.getElementById("txtAns"+i).value;
}
//add them all together
var finalTotal = 0;
for (var i = 0; i<seperateTotals.length; i++){
   finalTotal += seperateTotals[i];
}

//output them somewhere
someDiv.innerHTML = "Total = "+finalTotal;
```
of course that is untested etc, and of course you could simply keep a running count of the sets aswell.

Cheers,
Jamey


----------



## SerialChick (Aug 9, 2008)

Hi, i'm back again after a long absence with the same code.

I'm still trying to work out how to get the total at the end. The idea above is good, but I have several sections each with their own totals.

What i wanted to know is, if you say TextBox = document.getElementById("name" + num) and the actual element in the form does not exist, what will TextBox be? will it just equal null?
because then i could say something like

```
num = 0
total = 0

TextBox = document.getElementById("txtAns" + num)
AnsBox = document.getElementById("txtTotal")

while (TextBox != null){
    subtotal = parseFloat(TextBox.value)
    total = total + subtotal
    num = num + 1
    TextBox = document.getElementById("name" + num)
}
AnsBox.value = total
```
it works in theory, but for some reason not in practise.

Anyone have any ideas on this?


----------



## SerialChick (Aug 9, 2008)

I have a mock up using the code below.


```
<html>
<head>
<title>Basic Form</title>

<script language="javascript">

function Cal(num) {
var NumBox = document.getElementById("txtNum" + num);
var CostBox = document.getElementById("txtCost" + num);
var AnsBox = document.getElementById("txtAns" + num);

var Num = parseFloat(NumBox.value);
var Cost = parseFloat(CostBox.value);

var Ans = Num*Cost;
AnsBox.value = Ans;

var TotalBox = document.getElementById("txtTotal")

counter = 0
total = 0.0

TotalBox = document.getElementById("txtTotal");
SubTotalBox = document.getElementById("txtAns" + counter);

while (SubTotalBox != null) {
	SubTotal = parseFloat(SubTotalBox)
	
	total = total + SubTotal
	counter = counter + 1
	SubTotalBox = document.getElementById("txtAns" + counter);
	}

TotalBox.value = total

} 
</script>

<style>

.answer {
background-color:#0000FF;
color:#FF0000;
}

</style>

</head>

<body>
<form id="form1" name="form1" method="post" action="">

    <input type="text" name="txtNum0" id="txtNum0" value="0" onchange= "Cal(0)" />
    <input type="text" name="txtCost0" id="txtCost0" value="0" onchange= "Cal(0)"/>
    <input type="text" name="txtAns0" id="txtAns0" class="answer" readonly="true"/><br />
 
    <input type="text" name="txtNum1" id="txtNum1" value="0" onchange= "Cal(1)" />
    <input type="text" name="txtCost1" id="txtCost1" value="0" onchange= "Cal(1)"/>
    <input type="text" name="txtAns1" id="txtAns1" class="answer" readonly="true"/><br />
  
  	<input type="text" name="txtTotal" id="txtTotal" class="answer" readonly="true"/>
</form>
</body>
</html>
```
and everything works except the totals box which returns NaN.


----------



## jamiemac2005 (Jul 5, 2007)

Hey, if document.getElementById("ID") can't find the item with the specified ID it will return false (not null, the slight difference being that the variable is actually set).

So:

```
while(document.getElementById("txtAns" + counter)){//by default this will return true you could also use "!= true" like you have with null
//the code here will execute until "txtAns"+counter is not found
}
```
Cheers,
Jamey


----------

