我已经使用java脚本添加了多个文本框值..比如多个价格..我想计算总价 这是我自动生成文本框的脚本 $(文件)。就绪(函数(){
//iterate through each textboxes and add keyup
//handler to trigger sum event
$(".txt").each(function() {
$(this).keyup(function(){
calculateSum();
});
});
});
function calculateSum() {
enter code here
var sum = 0;
//iterate through each textboxes and add the values
$(".txt").each(function() {
//add only if the value is number
if(!isNaN(this.value) && this.value.length!=0) {
sum += parseFloat(this.value);
}
});
//.toFixed() method will roundoff the final sum to 2 decimal places
$("#sum").html(sum.toFixed(2));
}
我有html代码
<th>Description</th>
<th>Code</th>
<th>Qty</th>
</tr>
<tr id="Row2">
<th width="300">
<input type="text" name="desc" size="43" />
</th>
<th>
<input type="text" name="code" />
</th>
<th>
<input type="text" name="qty" size="10" class="txt"/>
</th>
</tr>
</table>
Total Qty:<span id="sum">0</span><input type="hidden" name="totalqty" align="right" id="sum" size="10" >
<button type="button" id="btnAdd">Add few more Rows!</button>
我有添加脚本的代码
<script>
$(document).ready(function(){
//iterate through each textboxes and add keyup
//handler to trigger sum event
$(".txt").each(function() {
$(this).keyup(function(){
calculateSum();
});
});
});
function calculateSum() {
var sum = 0;
//iterate through each textboxes and add the values
$(".txt").each(function() {
//add only if the value is number
if(!isNaN(this.value) && this.value.length!=0) {
sum += parseFloat(this.value);
}
});
//.toFixed() method will roundoff the final sum to 2 decimal places
$("#sum").html(sum.toFixed(2));
}
</script>
答案 0 :(得分:1)
每个函数都有两个参数
$(".txt").each(function(index, htmlElement){
$(htmlElement).keyup(function(event){
//do your code here
calculateSum();
})
});
你的calculateSum将是这样的
function calculateSum(){
$(".txt").each(function(index, htmlElement){
sum += parseFloat($(htmlElement).val());
});
}
每个函数中回调函数的第一个参数是所选元素数组中元素的索引号
和第二个参数是所选元素数组中当前所选元素(html输入元素)。