21
Oct '17

Cloning simple markup is usually a fairly trivial task in jQuery, using the .clone() function, however it becomes a major headache when there are form elements involved. jQuery’s clone function effectively works based on the raw HTML of the page and as such any changes that have since taken place within the DOM are ignored. This doesn’t sound like such a big deal until you realise that includes changes to all form input elements; the clone will have these all reset to their initial values.

I’ve written a little function to get round this issue, which simply ‘fixes’ the current values fo all input fields (except files) in the markup, allowing them to be cloned correctly:

function fixValues(element) {
    element.find('input[type=text]').each(function() {
        $(this).attr('value', $(this).val());
    });

    element.find('input[type=checkbox], input[type=radio]').each(function() {
        $(this).attr('checked', $(this).is(':checked') ? 'checked' : '');
    });

    element.find('select option:selected').each(function() {
        $(this).attr('selected', 'selected');
    });

    element.find('textarea').each(function() {
        $(this).html($(this).val());
    });
}

Just trigger this function on the element you want to clone, immediately before calling the jQuery clone function (or, if you’re feeling really enthusiastic, you could even extend the clone function itself) and your values should all be copied over as expected.