简体   繁体   中英

jQuery does not recognize cloned inputs

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.

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')
});

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

$('body').on('click', '#total-1', function() {

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