Search code examples
javascriptbootstrap-selectpicker

Refreshing a selectpicker with data-live-search ignoring text filter


I have a heavy multiple select and therefore I am currently adding options for a selectpicker multiple with data-live-search through Ajax while the user is typing. The refresh is properly updating the options but unfortunately it is also ignoring the current data-live-search text.

This is my way of doing it:

  1. Initialize the selectpicker with no options

  2. When the user is typing, I dynamically add an option then use the refresh method (working properly)

  3. If the user replace his text with something else it will add dynamically the other options but will show the first ones as well (that are not relevant with the user text filter)

$('#special_selectpicker').parent().find('input.form-control').on('input', function() {
  if ( $(this).val().length >= 3 ){
    $.ajax({
      url: "/get_objects/json/app_name/item",
      data: {
        filters: JSON.stringify([
            {
              column: "name__icontains",
              value: $(this).val()
            }
          ]),
        fields: JSON.stringify(['uppercase_name'])
      },
      success: function (result) {
        item_added = false
        json_result = JSON.parse(result)

        for ( const id in json_result['results'] ){
          item = json_result['results'][id]
          if( !option_cities.includes(item['pk']) ){
            option_cities.push(item['pk'])
            $("#special_selectpicker").append('<option value="' + item['pk'] + '">' + item['uppercase_name'] + '</option>')
            item_added = true
          }

        }

        if( item_added ){
          $('#special_selectpicker').selectpicker('refresh');
        }

      }
    });
  }
});

I can't find a way to ask the selectpicker to refilter based on the text filter. Am I doing something wrong ?


Solution

  • As my function does not get any new result with the same text given twice, if I have a new result I triggered the event input for the select-picker event which did the trick.