Search code examples
jqueryselectclone

User selections getting lost in jQuery clone?


The background is not so necessary to understand the issue, but a basic idea of what I'm trying to do: I have a form with various sections that can be expanded, edited, and collapsed again, and the state of the form fields are remembered each time. I want to offer the user the ability to "cancel" changes - if the user expands a section and makes changes, but then decides to revert to what the form section was previously (before he expanded it), they can click "cancel" and the fields will all revert. (This is essentially an "undo"/rollback button.) I am implementing this by using jQuery clone to clone the form section when expanding, and if the user hits "cancel", I replace the updated form section with the original clone.

The problem is that "select" element selections by the user do not seem to be included in the clone. I have constructed a basic jsfiddle to demonstrate this - if you try to select something in either section and then clone it, it is cloned without the selection.

Is there any way to get around this limitation? Is there another method I should use rather than clone?

I assume that I can manually code a loop that will copy all the selected values of all the selects, but this is rather hacky. Any smoother way to deal with this?


Solution

  • Based on your fiddle:

    $(function(){
        $('#sec1Clone').click(function(){
            $("#sec1 select option:selected").attr("selected", true);
            $('#sec1').clone(true).attr('id', 'cloneOfSec1').appendTo(document.body);
        });
         $('#sec2Clone').click(function(){
             $("#sec2 select option:selected").attr("selected", true);
            $('#sec2').clone(true).attr('id', 'cloneOfSec2').appendTo(document.body);
        });
    });
    

    That seems to work if it's an acceptable solution.