Search code examples
javascriptjquerybootstrap-multiselect

Select values in bootstrap multiselect based on data attributes in jquery


I'm rather new in jquery/bootstrap coding and want to achieve the following. I have a select (using bootstrap Multiselect) with several options. Within this list, I try to select all the options that match values of an array (list1 in below code). However, instead of looking at the value op the options, I need to check on a data-attribute of the option (list 2 in below code).

My dropdown

<form>
  <select class="form-control" id="list1" multiple="multiple">
    <option data-vendorid="001" value="001">some-value-1</option>
    <option data-vendorid="002" value="002">some-value-2</option>
    <option data-vendorid="003" value="003">some-value-3</option>
  </select>

  <select class="form-control" id="list2" multiple="multiple">
    <option data-vendorid="001" value="some-value-1">some-value-1</option>
    <option data-vendorid="002" value="some-value-2">some-value-2</option>
    <option data-vendorid="003" value="some-value-3">some-value-3</option>
  </select>
</form>

My script

var arr = [{
    "attr-1": "attr-value-1",
    "attr-2": "attr-value-2",
    "id": "001"
}, {
    "attr-1": "attr-value-1",
    "attr-2": "attr-value-2",
    "id": "003"
}];

//If I look for the default value, it works:
for (var i = 0; i < arr.length; i++) {
    $('#list1').multiselect('select', arr[i].id);
}

//So I tried something like this, but can't figure it out
for (var i = 0; i < arr.length; i++) {
    $('#list2').multiselect('select', $(arr[i]).data('vendorid'));
}

Check my updated fiddle!

Help is much appreciated


Solution

  • Based on your comments, I think you're trying to do a data mapping like this:

    var map = {};
    $('#list2').find('option').each(function(index, elem) {
        map[$(elem).data('id')] = elem.value;
    });
    
    for (var i = 0; i < arr.length; i++) {
        $('#list2').multiselect('select', map[arr[i]['id']]);
    }
    

    According to the docs of the multiselect jQuery plugin, the .multiselect('select', String|Array) method expects a string or an array of option values to be selected. As you are trying to do the selectoin based on other attributes you have to make a "dictionary" that maps your stored records to the option values. That's what the example above does.

    Update:
    I just have updated the code to reflect the exact attribute names in your Fiddle.