Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/405.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript jQuery-计算输入字段的总和,包括以后添加的字段_Javascript_Jquery_Dynamic_Sum - Fatal编程技术网

Javascript jQuery-计算输入字段的总和,包括以后添加的字段

Javascript jQuery-计算输入字段的总和,包括以后添加的字段,javascript,jquery,dynamic,sum,Javascript,Jquery,Dynamic,Sum,我有一个表单,您可以在其中添加更多输入字段。他们都有相同的班级。每当一个输入字段被更改时,我计算所有这些输入字段的总和 它适用于所有现有字段。当我尝试新添加的字段时,它就不再工作了 我想我可能不得不使用“现场”活动。但我不知道怎么做 这是我的代码: $('.price_item').change(function() { var ntotal = 0; $('.price_item').each(function() { ntotal += parseFloat($(th

我有一个表单,您可以在其中添加更多输入字段。他们都有相同的班级。每当一个输入字段被更改时,我计算所有这些输入字段的总和

它适用于所有现有字段。当我尝试新添加的字段时,它就不再工作了

我想我可能不得不使用“现场”活动。但我不知道怎么做

这是我的代码:

$('.price_item').change(function() {
   var ntotal = 0;
   $('.price_item').each(function() {
      ntotal += parseFloat($(this).val());
   });
});

我该怎么办?

您必须将事件处理程序放在文档上,因为您需要它来处理尚不存在的元素

$(document).on('change', '.price_item', function() {
    var ntotal = 0;
    $('.price_item').each(function(){
        ntotal += parseFloat($(this).val());
    });
});
添加JSIDLE:

使用like

应满足您的需要:

$(document).on('change', '.price_item', handlePriceItemChange);
function handlePriceItemChange(){
  var ntotal = 0;
   $('.price_item').each(function(){
      ntotal += parseFloat($(this).val());
   });
}

从jQuery 1.9开始,您不能使用.live(),因此应该使用.on()

试着这样做:

jQuery(function($){
$(document).on('change', 'input', function(){

    var ntotal = 0;
    $('.price_item').each(function(){
        ntotal += parseFloat($(this).val());
    });

    console.log('sum: ' + ntotal);

    //adds new input for testing
    $(this).after('<input type="text" class="price_item" />');
});               
});
jQuery(函数($){
$(文档).on('change','input',function()){
var ntotal=0;
$('.price_item')。每个(函数(){
ntotal+=parseFloat($(this.val());
});
console.log('sum:'+ntotal);
//添加新的测试输入
$(本)。在('')之后;
});               
});

工作起来很有魅力!感谢好听,没问题!
jQuery(function($){
$(document).on('change', 'input', function(){

    var ntotal = 0;
    $('.price_item').each(function(){
        ntotal += parseFloat($(this).val());
    });

    console.log('sum: ' + ntotal);

    //adds new input for testing
    $(this).after('<input type="text" class="price_item" />');
});               
});