Reputation: 3
How do I determine the correct number of textbox (input type="text") in an html form using Javascript. What I'm trying to do here is to compute the subtotal by providing the qty and price.
<script type="text/javascript">
function compute(){
var quant=new Array();
var price=new Array();
var stotal=new Array();
var tbox=new Array();
var elemlent=document.x.elements.length;
var dib=elemlent /3;
for(var i=0; i<dib; i++)
{
quant[i] = document.x.elements['qty[i]'].value;
price[i] = document.x.elements['cost[i]'].value;
stotal[i]= quant[i] * price[i];
tbox[i] = document.x.elements['subtotal[i]'];
if (tbox[i])
{
tbox[i].value = stotal[i];
}
}
}
</script>
<body>
<table border="1">
<form name="x">
<th>QTY</th>
<th>COST</th>
<th>SUBTOTAL</th>
<td>+</th>
<?php
for($i=0;$i<2;$i++){
?>
<tr>
<td><input type="text" name="qty[<?php echo $i; ?>]" value=""/></td>
<td><input type="text" name="cost[<?php echo $i; ?>]" value=""/></td>
<td><input type="text" name="subtotal[<?php echo $i; ?>]" value=""/></td>
<td><img src="add-icon.png" onmouseover="compute();"></td>
</tr>
<?php } ?>
</form>
</table>
</body>
I just can't seem to make this work when I add for loops.
Can you see what's wrong with my code?
Upvotes: 0
Views: 283
Reputation: 28598
Change:
['qty[i]']
to:
['qty[' + i + ']']
and similar for the other ones to make the above work. I suggest you change <input>
elements to provide the id, something along these lines:
<input type="text" id="qty[<?php echo $i; ?>]" name="qty[<?php echo $i; ?>]" value=""/>
Then, instead of:
quant[i] = document.x.elements['qty[i]'].value;
use:
quant[i] = document.getElementById(['qty[' + i + ']']).value;
Note also that you are going to get a string, so I suppose you'd like to use parseInt
and/or parseFloat
:
i.e. something like this:
quant[i] = parseFloat(document.getElementById(['qty[' + i + ']']).value);
Note, also, that you may want to consider checking for errors (e.g. if someone enters "qqaacc" in price field instead of "123.45").
Upvotes: 2