开发者

How to know the number of textbox in a form using javascript

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 typ开发者_如何学编程e="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?


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:

  • http://www.w3schools.com/jsref/jsref_parseInt.asp
  • http://www.w3schools.com/jsref/jsref_parseFloat.asp

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").

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜