Change inner elements id during clone

后端 未结 4 1282
天命终不由人
天命终不由人 2021-02-13 18:17

I\'m doing a clone of a DIV element on button click, I\'m able to change the value of ID of the DIV element I\'m cloning. But is it possible to change the id of the inner elemen

4条回答
  •  醉话见心
    2021-02-13 18:52

    I had a similar need to change the id of the clone and all its children. Posting my solution to help someone in the future. I wanted to change the ids and the names of all the children of the clone.

        $("#form").on('click', '.clone', function (e) {           
            e.preventDefault();
    
            var myid = this.id;  // id of section we are cloning i.e. section_1
            myid = myid.split('_');
    
            var num = 0;   
            // count existing sections
            $('.form_section').each(function(){
                num++;
            }); 
            num++; // new number for clone
            var newid = 'section_'+num;
            // make and change id of the clone
            var clone = $( "#section_"+myid[1] ).clone().attr("id", newid);
            // get clone children
            clone.children().find('input,textarea,button,a,select').attr('id', function( i, val ){ 
                 var oldid = val;
                 var newid = val + num;
                 clone.find("#"+val).attr("id", newid);
                 clone.find("#"+newid).attr("name", newid);
            });
    
            clone.appendTo( ".sections" );
    
        });
    

提交回复
热议问题