htmljqueryjsoncore-ui

How to set selected value of COREUI multiselect?


I this json response from an API.

 {"first_name":"Person 1","last_name":"Person 1","email":"person@test.com","role":2,"properties":[1,2]}

And the following coreui element:

<select class="form-multi-select" id="edit_properties" name="multi-select-edit_properties" multiple="" data-coreui-search="true" tabindex="-1" style="display: none;">
      <option value="1">consequatur</option>
      <option value="2">dolore</option>
      <option value="3">ab</option>
      <option value="4">eum</option>
      <option value="5">maxime</option>
</select>

I tried using this jquery code:

$("#edit_properties").val([data.properties]);

No errors in console, and the select element does not set selected values.


Solution

  • In order for the multi-select to render pre-selected values, each option must have an extra attribute selected="selected".

    <select class="form-multi-select" id="edit_properties" name="multi-select-edit_properties" multiple="" data-coreui-search="true" tabindex="-1" style="display: none;">
          <option value="1" selected="selected">consequatur</option>
          <option value="2" selected="selected">dolore</option>
          <option value="3">ab</option>
          <option value="4">eum</option>
          <option value="5">maxime</option>
    </select>
    

    You can achieve this by adding the selected attribute programmatically, when you get the response from the API.

    For example

    var response = JSON.parse('{"first_name":"Person 1","last_name":"Person 1","email":"person@test.com","role":2,"properties":[1,2]}');
    
    // Get the reference of the html element using the coreui js API
    var multiselect = coreui.MultiSelect.getInstance(document.querySelector("#edit_properties"));
    
    response.properties.forEach(function(elem) {
        document.querySelector(`#edit_properties option[value='${elem}']`).setAttribute("selected", "selected")
    });
    
    // update the element to render the selected options
    multiselect.update();
    

    Useful links: