6

All,

I have two select boxes :

  • Fruit select
  • FruitQuantity select

Depending on what option is selected in Fruit will affect the options of FruitQuantity.

So using select2, I wanted to replace all the options in a select simply by doing this.

var options = [];
            $.each(pageData.products[selectedFruit].quantities, function (key, value) {
                options.push({
                    text: value.quantity,
                    id: value.quantity,

                })
            });
            console.log(options.length);
            $quantitySelect.select2( { data : options });

The problem is that select2 is just appending the new data on to what exists already. I want it to clean out all the options and add the new ones.

Otherwise my select box is filling up with incorrect options.

I tried this from this question Clear dropdown using jQuery Select2

$quantitySelect.select2('data', null)

This does nothing though, it doesn't clear it.

Help me Obi Wan, you're my only hope.

Community
  • 1
  • 1
tomaytotomato
  • 3,788
  • 16
  • 64
  • 119

3 Answers3

17

Assuming you work with select2 4.0.0, and the following kind of HTML:

<select id="fruits">
    <option value="apple" selected>Apples</option>
    <option value="pear">Pears</option>
</select>
<select id="quantities"></select>

You'll need to listen to the "change" event on the "#fruits" control, and each time it changes, you-'ll need to re-populate your "#quantities" dropdown with relevant data.

Here's how it will look like:

var initQuantitiesDropdown = function () {
    var options = [];
    var selectedFruit = $("#fruits").val();
    $.each(pageData.products[selectedFruit].quantities, function (key, value) {
        options.push({
            text: value,
            id: key
        });
    })
    $("#quantities").empty().select2({
        data: options
    });
};

$("#fruits").select2().change(initQuantitiesDropdown);
initQuantitiesDropdown();

You can see this in action in this JSFiddle

Dethariel
  • 3,394
  • 4
  • 33
  • 47
  • 1
    If You need to have a placeholder , you need to add an empty option too like below `$("#quantities").empty().append('').select2({ data: options });` – Mohammad Qasim Sep 03 '19 at 07:31
6

First empty the list then re-initialize it again

$quantitySelect.empty().select2();

https://jsfiddle.net/qum29ken/

Emad Khalil
  • 803
  • 1
  • 8
  • 14
0

try this $quantitySelect.val(null).trigger("change"); assuming you have already initialize select2.

reference - https://select2.github.io/examples.html#programmatic

Karan
  • 2,102
  • 2
  • 22
  • 31