Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add a class to a Selectize option, dynamically?

When adding options to a select input, it's trivial to conditionally add a class, using jQuery:

$("#mySelect").append(
    $("<option></option>") 
        .text(myName)
        .val(myValue)
        .addClass(myBoolean ? "class1" : "class2")
);

My question is: how can I achieve the same effect using selectize.js?

I can use the following code to add an option (the variable mySelect refers to something like $("#mySelect")[0].selectize).

mySelect.addOption({
    value: productGrouping.id,
    text:  productGrouping.name
});

Adding a class option here doesn't work, and addOption() doesn't return anything, so I'm stuck as to how to do this. Is is possible?

like image 881
GordyB Avatar asked Oct 18 '22 03:10

GordyB


1 Answers

This is an excellent case for a SelectizeJS Plugin.

I wrote up one that is a simple example of what I think you want -- options marked with a "favorite: true" property have a new class, and style, added to them dynamically in the SelectizeJS widget.

selectize.plugins.js

Selectize.define('favorite_options', function(options) {
  options = $.extend({
        className : 'favorited'
    }, options);

  var favoriteOptionsClass = function(thisRef, options) {

    var self = thisRef;
    console.log({'self':self})

    var original = self.setup;
    self.setup = (function() {

        return function() {

          var option_render = self.settings.render.option;
          self.settings.render.option = function(option) {
            // "render" the original option to get the current HTML
            var html = option_render.apply(self, arguments);

            // modify HTML to add class
            var $html = $(html);
            var classes = $html.attr("class");

            if (option.favorite) {
              $html.addClass("favorite")
            }

            // return NEW $html element as HTML string
            return $('<div>').append($html.clone()).html();
          }

          original.apply(self, arguments);
        };
    })();
  }

  favoriteOptionsClass(this, options);
  return;
});

app.js

$("#wiki-select-property").selectize({
  maxItems: 1,
    valueField: 'id',
    labelField: 'title',
    searchField: 'title',
    plugins: [
      'favorite_options' 
    ],
    options: [
        {id: 1, title: 'Spectrometer', favorite: true, url: 'http://en.wikipedia.org/wiki/Spectrometers'},
        {id: 2, title: 'Star Chart', favorite: false,  url: 'http://en.wikipedia.org/wiki/Star_chart'},
        {id: 3, title: 'Electrical Tape', favorite: false,  url: 'http://en.wikipedia.org/wiki/Electrical_tape'}
    ]
})

Working Plnkr Example

like image 112
RoboBear Avatar answered Oct 21 '22 06:10

RoboBear