Clone issue - jquery

I am using this plugin

Now I am making a way to clone the select dropdown. Button for adding cloned divs. So, the user has an initial drop-down list, but he can add more. The div key is cloned.

The main problem is that when I clone a div, the combobox is associated with the initial combobox, not the new cloned one. Result: all drop-down lists of new cloned divs have an event to open the selected one associated with the first.

enter image description here

Script to call the plugin

<script language="javascript" type="text/javascript"> $(document).ready(function() { $(".mydds").msDropDown(); }) </script> 

Script for cloning

 <script type="text/javascript"> $(document).ready(function() { $('#adicionar').live('click', function(){ var num = $('.linguas').length; var newNum = new Number(num + 1); var newElem = $('#copiar' + num).clone(true).prop('id', 'copiar' + newNum); newElem.children(':text').prop('name', "myformdata[languages" + newNum + "]").prop('languages', 'languages' + newNum).val(''); $('#copiar' + num).after(newElem); $('#apagar').prop('disabled', ''); }); </script> 

Any idea to solve the problem? Basically, I think the event associated with the dropdown is not copied ... thanks

+6
source share
2 answers

Assuming you only have one drop-down list per cloned item, you can use

 $('#adicionar').live('click', function(){ var num = $('.linguas').length; var newNum = new Number(num + 1); var newElem = $('#copiar' + num).clone(true, true).attr('id', 'copiar' + newNum); var id = newElem.find('select').msDropDown().data('dd').get('id'); newElem.find('[id]').each(function(){ $(this).attr('id',this.id.replace(id,'customid_' + newNum,'g') ); }); $('#copiar' + num).after(newElem); newElem.find('select').msDropDown(); }); 

The problem is that the plugin provides an identifier to the original select element and uses this id to create other elements, as well as to reference its associated select .

You will need to change all these identifiers, as well as the link .. (the code above does just that.)

demo http://jsfiddle.net/gaby/CXBZR/3/

+3
source

In the script, you call .clone(true) . This parameter true clones events and data.

From API

.clone( [ withDataAndEvents ] )
withDataAndEvents: a logical indication of whether event handlers should be copied along with the elements. Starting with jQuery 1.4, item data will be copied as well.

If you delete this or set it to false, this will stop events from cloning to your new divs.

+1
source

Source: https://habr.com/ru/post/890197/


All Articles