Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

problem when clone - jquery

i am using this plugin

Now i am doing a way to clone the select dropdown. A button to add cloned divs. So, an user have a initial dropdown, but he can add more. The div is cloned.

The main problem is that when i clone the div, the dropdown is associated to initial dropdown and no to the new, that is cloned. The result is: all dropdowns of the new cloned divs have the event to open the select associated to the first.

enter image description here

Script to call the plug in

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

</script>

script to clone

<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 to dropdown is not copied... thanks

like image 944
user455318 Avatar asked Jun 09 '11 22:06

user455318


2 Answers

Assuming you have only one dropdown per cloned element, 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 gives an id to the initial select element, and uses that id to create other elements and also to refer to its related select.

You will need to modify all those ids as well as the reference.. (the code above does just that..)

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

like image 114
Gabriele Petrioli Avatar answered Oct 04 '22 14:10

Gabriele Petrioli


In your script you are calling .clone(true). This true parameter is cloning the events and data.

From the API

.clone( [ withDataAndEvents ] )
withDataAndEvents: A Boolean indicating whether event handlers should be copied along with the elements. As of jQuery 1.4, element data will be copied as well.

If you remove this, or set it to false, this will stop the events from being cloned onto your new divs.

like image 40
Alastair Pitts Avatar answered Oct 04 '22 13:10

Alastair Pitts