Looping through form elements in javascript and adding the fetched values
I'm trying to create a simple form which calculates the values in every input field which has subtotal at the start of the name attribute:
<script type="text/javascript" src="jq.js"></script>
<script type="text/javascript">
$(function(){
var qty = 0;
var price = 0;
var subtotal = 0;
var qty_r = [];
var price_r = [];
var subs_r = [];
var total = 0;
$('input[name^=qty]').each(function(index) {
qty_r[index] = $(this).val();
});
$('input[name^=price]').each(function(index){
price_r[index] = $(this).val();
});
var j = 0;
for(j = 0; j<=2; j++){
subs_r[j] = parseInt(price_r[j]) * parseInt(qty_r[j]);
}
$('input[name^=subtotal]').each(function(index){
$(this).val(subs_r[index]);
});
$('input[name^=qty]').keyup(function(){
var basis = $(this).attr("id");
var numbasis = basis.toString();
qty = $(this).val();
price = $('input[name=' + numbasis + ']').val();
subtotal = parseInt(qty) * parseInt(price);
$("#subtotal" + numbasis).val(subtotal);
This is the part where I'm having trouble:
$("input[name=subs]").each(function(index){
total = parseInt($(this).val()) + total;
$('#total').val(total);
});
});
});
</script>
And here's where the data which being calculated comes from:
<?php $products = array(array("prodname"=>"mais", "qty"=>5, "price"=>15), array("prodname"=>"strawberry", "qty"=>7, "price"=>25), array("prodname"=>"kambing", "qty"=>14, "price"=>3)); ?>
<table border="1">
<tr>
<th>Product</th>
<th>Qty</th>
<th>Price</th>
<th>Subtotal</th>
</tr>
<?php foreach($products as $key=>$prods){
?>
<tr>
<td><input type="text" name="prodname<?php echo $key; ?>" value="<?php echo $prods['prodname']; ?>"/></td>
<td><input type="text" id="<?php echo $key; ?>" name="qty<?php echo $key; ?>"开发者_如何学编程 value="<?php echo $prods['qty']; ?>"/></td>
<td><input type="text" name="<?php echo $key; ?>" id="price<?php echo $key; ?>" value="<?php echo $prods['price']; ?>"/></td>
<td><input type="text" name="subs" id="subtotal<?php echo $key; ?>" /></td>
</tr>
<?php } ?>
</table>
Total: <input type="text" id="total"/><br/>
The problem is that I'm always getting NaN as a result.
If you're getting NaN you're probably trying to parseInt something that has a return value of NaN. You can do
$("input[name=subs]").each(function(index) {
total = (parseInt($(this).val(), 10) || 0) + total;
$('#total').val(total);
});
Wich will always only add numbers to total.
Let's make that a possible answer, try using:
total = parseInt($(this).val()) + parseInt(total);
Also make sure $(this).val() has a proper value everywhere. If it's blank you will get NaN as a result. For almost any other you will get the right result: http://www.w3schools.com/jsref/jsref_parseInt.asp
It looks like you might be using the wrong selector to set the subtotal values you're using to do the final calculation. Shouldn't it be this:
$('input[id^=subtotal]').each(function(index){
$(this).val(subs_r[index]);
});
精彩评论