Search code examples
javascripthtmljqueryappend

Creating Custom Select at Run Time


I recreated my issue on Fiddle: https://jsfiddle.net/RayLove21/k05xhgaL/30/

This is the function I'm utilizing to append the custom select.

     function CREATE_OPTION() {
        var varForm = '<label id="img_category_label" class="field" for="img_category" data-value="">';
        varForm += '<span>Category</span>';
        varForm += '<div id="img_category" class="psuedo_select" name="img_category">';
        varForm += '<span class="selected"></span>';
        varForm += '<ul id="img_category_options" class="options">';
        varForm += '<li class="option" data-value="opt_1">Option 1</li>';
        varForm += '<li class="option" data-value="opt_2">Option 2</li>';
        varForm += '</ul>';
        varForm += '</div>';
        varForm += '</label>';
        $(varForm).appendTo("#modal-content");
      }

If you notice, the custom select works great when created at design time. When I try to insert the custom select at run time utilizing appendTo, it creates the box but the drop-down functionality doesn't work.

I tried both jquery and jscript methods of insertion but both fail at run time. I can create input boxes at run time or even regular select options at run time but these custom ones fail. I expect if it's inserting all the html code at run time it should function the same.


Solution

  • First, I think you should be using select and options HTML tags instead of ul and li for this functionality (suggested by your use of class="option").

    Here is a working code that behaves exactly as you've described:

    function CREATE_OPTION() {
            var varForm = '<label id="img_category_label" class="field" for="img_category" data-value=""></label>';
            varForm += '<span>Category</span>';
            varForm += '<div id="img_category" class="psuedo_select" name="img_category">';
            varForm += '<span class="selected"></span>';
            varForm += '<select id="img_category_options" class="options"><option class="option" data-value="opt_1">Option 1</option><option class="option" data-value="opt_2">Option 2</option></select>';
            varForm += '</div>';
            console.log("varForm", varForm)
            $(varForm).appendTo("#modal-content");
          }
    

    Second, you're wrapping the elements in label HTML tag which is not how it is intended for use. You should be closing the label tag first, then introduce the options to be selected. I see the options render when I close out the label tag before the div. Again, I suggest using select and options tags for this.

    Lastly, I recommend using console to view the value of varForm. I see why you're appending the HTML elements to varForm (for maintainability I suppose), but this clouds the final unit of HTML generated.