[英]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 我的问题是,我需要
#subtotal
添加的每个实例.grouptotal
,但#subtotal
当它到达它的输入来自未更新
$('.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. 如果我将数字手动放在
.grouptotal
则#subtotal
将更新。 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
数量*系统将自动更新我的
.grouptotal
How do I make it so #subtotal
will take the .grouptotal
s and add them up automatically? 如何使
#subtotal
接受.grouptotal
并自动添加它们? I've tried changing $(document).on('change', '.grouptotal', function(){
"change" to 'input' and a couple others, but no luck. 我试过将
$(document).on('change', '.grouptotal', function(){
“ change”更改为'input'和其他几个,但是没有运气。
Also, it must work if the #clone
button is clicked to duplicate the group. 同样,如果单击
#clone
按钮以复制组,则它必须能够正常工作。
使用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'.
为了解决这个问题,我添加了一个显式触发器“ .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
可能不是您要寻找的解决方案,但它似乎有效
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.