Javascript – Adding html elements from variable using jquery

javascriptjqueryjquery-pluginsjquery-selectorsjquery-ui

I am trying to add elements to specific div, but not using clone(), because i need fresh copy of original elements on every add, mainly because elements are draggable and their values are being change by user? So i have my html in variable, i need to take this elements and add them on click to another elem. ?

$(document).ready(function (e) {

var $gElem = $(
    '<div class="distributionWrapper" id="element_0">' +
        '<div class="cbox cboxQuarterWidth">'  +         
            '<select id="combobox100">'+
                '<option>1</option>'+
                '<option>2</option>'+
            '</select>'+
        '</div>'+
        '<div class="help"><a href="javascript:;"></a></div>'+
        '<div class="cbox cboxEighthWidth"><span>'+
            '<select id="combobox200" name="PeriodId">'+
                '<option>1</option>'+
                '<option>2</option>'+
            '</select>'+
        '</span></div>'+
        '<div class="clear" id="clearDistribution"><a href="javascript:;"></a></div>'+
        '<div class="add" id="addDistribution"><a href="javascript:;"></a></div>'+
    '</div>'
);

    $('.mainSearch').html($gElem); // initial load of element
    $("#combobox100").combobox();
    $("#combobox200").combobox();

var counter = 1;
$('.add').live('click', function () {
    if ($('.distributionWrapper').length === 6) return;
    //var el = $('.distributionWrapper:first').clone().attr('id', 'element_' + ++counter).appendTo('.mainSearch');
    $('.mainSearch').add($gElem).attr('id', 'element_' + ++counter);
     // here on click add gElem to .mainSearch and set atribute to .distributionWrapper

});

$('.clear').live('click', function () {
    if ($('.distributionWrapper').length === 1) return;
    $(this).parents('.distributionWrapper').remove();
});

});

Any ideas?

Best Answer

try this

$('.mainSearch').append($gElem);
$('.mainSearch').children('.distributionWrapper:last').attr('id', 'element_' + ++counter);