简体   繁体   中英

Select2 not rendering correctly

The below code works perfectly without calling select2 on the element. It adds all the options in and renders as should.

let selectInput = $('<select ' +
    'class="checklist-input" ' +
    'id="' + inputId + '" ' +
    'data-checklist-item-field="' + field + '" ' +
    'data-checklist-item-id="' + itemId + '" ' +
    (disabled ? 'disabled' : '') +
    '>');

$.each(data.summary_input_options, (_, val) => {
    selectInput.append(`<option value="${val.value}">${val.value}</option>`);
});

selectInput.val(value);

return selectInput;

However, the second I add a select2 call to the jQuery object things go weird, and the select2 fails to show most of the time, and if it does happen to show up - the second I change the value in the select it goes away again.

selectInput.val(value).select2();

It appears select2 is getting called correctly but is not inserting the HTML to render a select, because as you can see below, select2 is correctly inserting it's accessibility tags into the original select:

<select class="checklist-input select2-hidden-accessible" id="checklist-summary-52" data-checklist-item-field="summary" data-checklist-item-id="52" data-select2-id="checklist-summary-52" tabindex="-1" aria-hidden="true">
    <option value="Yes" data-select2-id="29">Yes</option>
    <option value="No">No</option>
    <option value="Maybe">Maybe</option>
</select>

If anyone has encountered this issue before or has any ideas please let me know

You have missed the css class ie select2 . Please add it.

You must append the html to DOM first then call the select2() function.

<select class="checklist-input select2 select2-hidden-accessible" id="checklist-summary-52" data-checklist-item-field="summary" data-checklist-item-id="52" data-select2-id="checklist-summary-52" tabindex="-1" aria-hidden="true">
   <option value="Yes" data-select2-id="29">Yes</option>
   <option value="No">No</option>
   <option value="Maybe">Maybe</option>
</select>

// try with this small change also (optional).
selectInput.val(value);
selectInput.select2();

Select2 is expecting the select to already be in the DOM.

Your code (as provided) does not (yet) add it to the DOM, so select2 doesn't know where to add its elements.

You could try to add a wrapper to selectInput and specify the dropdownParent to that wrapper, but it's unlikely to work as select2 will try to find that parent in the DOM to make its changes.

Solution: Add the select to the DOM first before changing it to a select2.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM