Search code examples
javascriptjqueryhtmlbootstrap-select

jQuery - <option> being added both inside <select> and after it


I'm trying to iterate over a group of <select> objects. For each one, I need to add a series of <option> tags to it. These options allow the user to select a color that will be stored in a database. As an aside, I'm using the bootstrap-select plugin to handle styling of the <select> objects, but I don't think that this is relevant to my post.

The array of <option> tags is learned from a group of hidden fields that is loaded at run time from the database. Thus it is not known until then, so all of this has to happen dynamically. Each of those hidden fields belongs to the class 'color_list', so iteration is very easy.

My code works insofar as I am able to update the <select> objects correctly. However, my code also seems to be duplicating these <option> tags after the <select> tag is closed, which screws up my DOM. A picture is worth a thousand words, right?

enter image description here

Notice how each individual <option> tag is repeated once inside the <select> tag (correct) and again outside of it (incorrect)? The tags that are added outside of the <select> tag are actually adding new color blocks below the drop down list.

In my jQuery code, I am only appending it a single time, so I don't know why this is happening.

function updateColorPickers() {

    // iterate over each color picker
    $( ".colorpicker" ).each(function(i, picker) {

        // and add each color as an option to it
        $(".color_list").each(function(j, elem) {
            var str  = "<option class='color_opt' style='background:";
            str     += $(elem).val();
            str     += "'>";
            str     += $(elem).val();
            str     += "</option>";

            $(picker).append(str);
        });

        $(picker).selectpicker('refresh');
    });
}

Solution

  • It's because you have two elements with class colorpicker. You are appending it to select.colorpicker and div.colorpicker

    That is, $('.colorpicker').length == 2

    You can likely fix it by using $('select.colorpicker').each