tomaytotomato
tomaytotomato

Reputation: 4028

Replacing select2 options?

All,

I have two select boxes :

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.

Upvotes: 7

Views: 14536

Answers (3)

Dethariel
Dethariel

Reputation: 3624

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

Upvotes: 17

Emad Khalil
Emad Khalil

Reputation: 823

First empty the list then re-initialize it again

$quantitySelect.empty().select2();

https://jsfiddle.net/qum29ken/

Upvotes: 7

Karan
Karan

Reputation: 2112

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

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

Upvotes: 0

Related Questions