0

JQuery does not recognize cloned objects, I have a Jquery code which clones a div and changes the name of the inputs inside it, the thing is that I need to perform certain functions with those cloned inputs and I am checking that jQuery does not recognize them, like If they did not exist, I leave you here the code, thanks in advance.

Jquery code cloning and ID renaming (work perfect code)

    $('#div-materiales-{{$num}}').clone().appendTo('#material-form').prop('id', 'div-materiales-' + i);

    $('#div-materiales-' + i).find('input.total').attr('id', "total-" + i);
    $('#div-materiales-' + i).find('input.total').attr('name', "total-" + i);
i++;

Code that should show an alert when clicking the total input-1

$(document).ready(function () {

$("#total-1").click(function() {


    alert('funciona');

});

});

PS: I understand that it is the cloning that gives me problems because the initial total is total-0 and the code above but with total-0 the alert jumps but as I have commented here the total-1 (which would be the cloning) does not I get the alert to jump.

  • 1
    Does this answer your question? [Event binding on dynamically created elements?](https://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) – Lapskaus Jun 03 '20 at 13:08

2 Answers2

1

Use "on" for dynamic bindings

$("body").on('click','#total-1',function(){ // Previously i had issue here for dynamic bindings
 console.log('clicked')
});

$("body").on('keyup','#total-1',function(){
 console.log('key up')
});
NoobX
  • 125
  • 6
  • and in case you want to use keyup instead of on? – David Robles Jun 03 '20 at 14:19
  • I have edited the code for keyup and dynamic bindings both previously i made a mistake which is corrected now further here is the snippet https://codepen.io/usman-shahid/pen/PoZoMxj – NoobX Jun 04 '20 at 06:17
0

You need to use on, and attach the event to an element that always exists:

$('body').on('click', '#total-1', function() {
iddo
  • 749
  • 3
  • 11