Search code examples
javascriptjqueryvisualforceapex

jQuery.each iterating over list twice when there are three objects in it. Javascript


There are three objects inside plan_unit_list_items, but only two li are appended to my ul. Can anyone tell me why this might be?

var plan_unit_list_items = {!planUnitList}; // APEX METHOD
var openPlanUnitList = function (unitdiv) {
    jQuery('div.plan_unit_dropdown').remove();
    var plan_unit_dr = jQuery('<div>')
        .addClass('plan_unit_dropdown')
        .append('<ul>');
    jQuery.each(plan_unit_list_items,

    function (idx, val) {
        jQuery('.plan_unit_dropdown ul').append(
        jQuery('<li>')
            .addClass('plan_unit_list_items')
            .text(val.Name))
        plan_unit_dr.appendTo(unitdiv);
    })
}

(And I apologise if 'iterating' is the wrong terminology in the question)


Solution

  • If I understand your code, it looks like you are creating a ul and then trying to append lis to it, but you are using the following selector to select the ul from the DOM when it hasn't yet been added to the DOM until after the first iteration:

    jQuery('.plan_unit_dropdown ul')
    

    So on the first iteration, no appending happens. Since you already have access to the newly-created ul, why not just append directly to that rather than re-selecting it?

    var openPlanUnitList = function (unitdiv) {
        jQuery('div.plan_unit_dropdown').remove();
        var plan_unit_ul = jQuery('<ul>'),
            plan_unit_dr = jQuery('<div>')
                .addClass('plan_unit_dropdown')
                .append(plan_unit_ul);
    
        plan_unit_dr.appendTo(unitdiv);
    
        jQuery.each(plan_unit_list_items, function (idx, val) {
            plan_unit_ul.append(jQuery('<li>')
                                  .addClass('plan_unit_list_items')
                                  .text(val.Name));
        });
    };