Search code examples
javascriptjqueryhtmlmulti-selectbootstrap-multiselect

Auto check saved data in jQuery Multiselect


I am using this jQuery Multiselect plugin https://github.com/nobleclem/jQuery-MultiSelect to convert all my select boxes that have the multiple attribute enabled in to drop down boxes with check boxes. I load the options in the select box from a database. Upon the form submission I can save the multiple selected data, but when I retreive data back from the database I cannot display the saved data back in the multi select box by checking matching check boxes.

The multiselect plugin has a loadOptions method, but using that method I have to generate all option data with option name, option value and the check status, and set it to the multiselect plugin. How can I easily do this if I have an array of data which must be checked/selected in the multiple select plugin?

HTML

<select name="abc" id="abc" multiple title="Test Number?">
    <option value="1">Test 1</option>
    <option value="2">Test 2</option>
    <option value="3">Test 3</option>
    <option value="4">Test 4</option>
    <option value="5">Test 5</option>
</select>

JS (I have more than one multiple select boxes and initiate them as shown below)

$.each($("select[multiple]"), function (key, selectbox) {
    $("#" + selectbox.id).multiselect({
        texts: {placeholder: $("#" + selectbox.id).attr("title")}
    });
});

My saved data array is [1,3,4] I need to set these saved data to the select box and check the check boxes without going through the loadOptions method.


Solution

  • You could use jQuery .filter() function on your select options to preselect those wanted before initializing the multiselect plugin.

    Here,

    $('option',this).filter((_,e) => saved_data.includes(+e.value)).prop('selected',true);
    

    Preselects every option, before the .multiselect() call.

    let saved_data = [1, 3, 4];
    
    $('select[multiple]').each(function() {
      $('option', this).filter((_, e) => saved_data.includes(+e.value)).prop('selected', true);
    
      $(this).multiselect({
        texts: {
          placeholder: $(this).attr("title")
        }
      });
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://springstubbe.us/projects/demos/jquery-multiselect/scripts/index.js?1523890673"></script>
    <link rel="stylesheet" href="https://springstubbe.us/projects/demos/jquery-multiselect/styles/index.css?1518818712">
    
    <select name="abc" id="abc" multiple title="Test Number?">
      <option value="1">Test 1</option>
      <option value="2">Test 2</option>
      <option value="3">Test 3</option>
      <option value="4">Test 4</option>
      <option value="5">Test 5</option>
    </select>