jquerybootstrap-4bootstrap-selectpicker

Dynamically Set Selected Options of Multi SelectPicker


I have a selectpicker, and I know the syntax to set the selected options of it via javascript:

$('.mySelectPicker').selectpicker('val', ['one', 'two', 'three']);

I'm trying to build a string in a loop: each time the loop iterates, this gets added (some PHP):

options += '\'' + '<?= $name ?>' + '\', ';

Then, I try to set the selected options like this:

$('.mySelectPicker').selectpicker('val', [options]);

However, there is something wrong with the syntax where I put "options". I am getting an error that says "Unexpected string". I think I'm referencing the options variable incorrectly. (I set it correctly a bit earlier in the code as var options = ""; )


Solution

  • The answer ended up being syntactically like this:

    var options = []; options.push('Mustard'); options.push('Relish'); $('.selectpicker').selectpicker('val', options);
    

    User Taplar provided the answer. Thank you!