简体   繁体   中英

Jquery - Sum of cloned elements won't work with input from function

Here's my code:

$(document).ready(function() {
  $('#clone').click(function() {
    var target = $(this).closest('.groupcontainer');
    target.clone(true, true).insertAfter(target);
  });

  $('.input').on('input',function(){
    $(this).parent().children('.grouptotal').val($(this).val() * $(this).parent().children('.input2').val());
  });

  $('.input2').on('input', function(){
    $(this).parent().children('.grouptotal').val($(this).val() * $(this).parent().children('.input').val());
  });
});  

$(document).on('change', '.grouptotal', function(){
  var sum = 0;
    $('.grouptotal').each(function(){
    sum += +$(this).val();
    });
    $('#subtotal').val(sum);
});

My issue is that I need #subtotal to add every instance of .grouptotal , but #subtotal is not updating when it gets it's input from

$('.input').on('input',function(){
  $(this).parent().children('.grouptotal').val($(this).val() * 
  $(this).parent().children('.input2').val());
  });

$('.input2').on('input', function(){
  $(this).parent().children('.grouptotal').val($(this).val() *   
  $(this).parent().children('.input').val());
  });

#subtotal will update if I manually put numbers in .grouptotal however. Can someone explain to me what I'm missing?

Here's the Fiddle . It looks kind of sloppy but it gives the idea.

Quantity * System will automatically update my .grouptotal

How do I make it so #subtotal will take the .grouptotal s and add them up automatically? I've tried changing $(document).on('change', '.grouptotal', function(){ "change" to 'input' and a couple others, but no luck.

Also, it must work if the #clone button is clicked to duplicate the group.

使用val('value')以编程方式设置值时,不会触发change事件,您必须实际触发它

$(this).parent().children('.grouptotal').val( $(this).val() ).trigger('change')

Let's try this again. Evidently, changing the grouptotal values programmatically does not trigger the change event. I would have thought it would, so your code looked right to me. To fix, however, I added an explicit trigger of '.grouptotal'. You can see the fiddle here .

just add the code:

('.grouptotal').change();

to both of your handlers that sum from inputs. that might not be the solution you are looking for, but it seems to work

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM