Morpheus
Morpheus

Reputation: 997

jQuery change doesn't work for 2 parts which are added dynamically

I have a bunch of js code that can be done easier but not sure how.

The problem is that I'm using 2 calculators to calculate values...

One is active while drag n drop is usable and then it is disabled for mobile resolutions... and the second one is active only on mobile resolutions.

In any case I have this:

items = ['item 22', 'item 23']
output = []
for (var i = 0; i < items.length; i++) {
    output.push('<p>' + items[i] + '<input class="total-items" value="0" />' + '</p>');
}
$('#total-elements').html(output.join(""));
$(".total-items").change(function(e) {
    calculateTotal();
});

and (difference is in input part this one below has onClick() )

c = ['item 1','item 2', 'item 3']
o = []
for (var i = 0; i < c.length; i++) {
    o.push('<p>' + c[i] + '<input class="total" value="0" />' + '<a href="#" class="remove-link" onClick="deleteRecord(' + i + ');" class="delete-item">x</a></p>');
}
$('#total').html(o.join(""));
$(".total").change(function(e) {
    calculate();
});

Code is placed inside document ready... The problem is with that onClick part, if that (deleteRecord()) function is placed inside document ready, then it doesn't work (I get ReferenceError: 'functionName' not defined... When I placed it outside document ready and then I need to move some other parts in order to get it working but now, when I click to remove one item from the list it will remove it which is ok but then if I try to add values to use calculator it will not calculate them since that .change() doesn't trigger at all...

If add it like this outside of document ready,

$(document).change(".total", function(e) {
  calculate();
});

then calculateTotal() which is placed inside document ready won't work...

So I am not sure how to make them both to work...

Any suggestions?

Thanks.

Upvotes: 1

Views: 118

Answers (2)

Zakaria Acharki
Zakaria Acharki

Reputation: 67505

.change() doesn't trigger at all...

That because your inputs .total-items and .total are added dynamically to the DOM by javascript so you have to use event delegation on() :

$("body").on("change", ".total", function(e) {
     calculate();
});

$("body").on("change", ".total-items", function(e) {
     calculateTotal();
});

Hope this helps.

Upvotes: 3

Piyush.kapoor
Piyush.kapoor

Reputation: 6803

Use event delegation

$(document).on('change',".total", function(e) {
     calculate();
});

$(document).on('change',".total-items", function(e) {
     calculateTotal();
});

Upvotes: 1

Related Questions