R
R
Roman Matveev2022-02-24 07:37:47
JavaScript
Roman Matveev, 2022-02-24 07:37:47

How to highlight certain options in select2?

Good day!
I use for select - plug-in SELECT2 .
In select there is such a grouping by category (see below), but you can only select option, but the task is to select not only subcategories in particular cities, but categories too, and in this case this cannot be done when I do not break it into groups by removing optgroup then I display everything in one option list .

So this is the essence of the question, how to select certain options in SELECT2 and in particular categories, put a class on them or just wrap them in a tag so that you can select them, since select2 will convert everything into a list using ul>li

<select>
  <optgroup label="Группа 1">
    <option value="AK">Alaska</option>
    <option value="HI">Hawaii</option>
  </optgroup>
  <optgroup label="Группа 2">
    <option value="CA">California</option>
    <option value="NV">Nevada</option>
    <option value="OR">Oregon</option>
    <option value="WA">Washington</option>
  </optgroup>
  </select>


select2 has such an opportunity to make a template for the list, but I can’t do it in order to somehow highlight the options I need

function formatState (state) {
  if (!state.id) {
    return state.text;
  }
  var baseUrl = "/user/pages/images/flags";
  var $state = $(
    '<span><img src="' + baseUrl + '/' + state.element.value.toLowerCase() + '.png" class="img-flag" /> ' + state.text + '</span>'
  );
  return $state;
};

$(".js-example-templating").select2({
  templateResult: formatState
});

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question