Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select all options using Selectize?

I am building a form using the jQuery selectize plugin. Now I am trying to build a method to select all options in the selectbox and display them as selected.

This is the code I use:

$('#select_all').click(function() {

          $('#project_user_ids option').prop('selected', true);

          $('#project_user_ids').selectize();

        });

It works to select all options but they are not shown in the selectbox. I need to a way of "refreshing" the options and showing the selected options in the box.

How can I do this?

like image 794
Jonathan Clark Avatar asked Feb 12 '23 15:02

Jonathan Clark


1 Answers

If you want to dynamically select all options using selectize plugin first you have to initialize plugin and get its instance.

Using the setValue() method you can change the value of the control. For example: selectize.setValue(['value1', 'value2']);

Using the setValue() it is possible to set all values using simple method from underscore or lodash. selectize.setValue(_.keys(selectize.options));

Complete code should look like this:

var $projectUserIds = $('#project_user_ids').selectize(); // Selectize plugin initialization
var selectize = $projectUserIds[0].selectize; // Get selectize instance

$('#select_all').click(function() {
    selectize.setValue(_.keys(selectize.options)); // Set all selectize options using setValue() method
});
like image 97
piotros Avatar answered Mar 11 '23 14:03

piotros