Как сказать Select2 для поиска из data-attr в дополнение к тексту опции (поиск по нескольким атрибутам в теге select2) - PullRequest
0 голосов
/ 07 марта 2020

У меня есть select2 в моем приложении rails для имен клиентов, теперь функция поиска хорошо работает с именами клиентов, поскольку в тексте опции задано имя клиента, теперь я хочу, чтобы select2 также выполнял поиск для contact_no клиента. И я устанавливаю contact_no клиента в data-attr в каждом теге option. Итак, как можно выполнить поиск из data-attr в дополнение к тексту опции. Заранее спасибо.

Редактировать Вот это HTML

<select>
    <option value="1" data-contact-no="9898989898">Zamir</option>
    <option value="2" data-contact-no="6767676767">Manihar</option>
    <option value="2" data-contact-no="666666">Zimmie</option>
</select>

и JavaScript

$("select").select2();

1 Ответ

0 голосов
/ 07 марта 2020

Я нашел решение, просто инициализирую select2 как:

function matchCustom(params, data) {
// If there are no search terms, return all of the data
if ($.trim(params.term) === '') {
  return data;
}

// Do not display the item if there is no 'text' property
if (typeof data.text === 'undefined') {
  return null;
}

// `params.term` should be the term that is used for searching
// `data.text` is the text that is displayed for the data object
if (data.text.indexOf(params.term) > -1 || data.element.getAttribute('data-contact-no').indexOf(params.term) > -1) {
  var matchedData = $.extend({}, data, true);

  // You can return matched objects from here
  return matchedData;
}

// Return `null` if the term should not be displayed
return null;
}

$("select").select2({
  matcher: matchCustom
});

Любое другое решение будет оценено. Спасибо

...