javascriptjqueryjquery-clone

Is there a way to update a clone() source based on change to the cloned element in jquery?


I have a cloned element that contains a checkbox input. When the cloned element is unchecked, I need the source element to also be unchecked. Is there a way to do this in jQuery? Or am I going about this the wrong way (i.e. using clone())? I should mention that my question is similar to this SO question except I need to update the original element when the cloned element changes, not simply maintain a reference.


Solution

  • Since it's a checkbox and you're specifically concerned with checking/unchecking the box, you can listen for the event 'change' which will fire every time the box's checked status changes.

    var copy = $('#my-element').clone();
    
    copy.change(function(){
        $('#my-element').replaceWith(copy.clone());
    });