Replacing select2 options?
Asked Answered
B

3

7

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.

Brigittebriley answered 10/11, 2015 at 9:27 Comment(2)
can u pls create fiddle (from jsfiddle.net) ... it will help a lotFilibertofilibuster
What version of select2 are you using? 3.5.x or 4.0.0?Recommit
R
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

Recommit answered 10/11, 2015 at 11:56 Comment(1)
If You need to have a placeholder , you need to add an empty option too like below $("#quantities").empty().append('<option></option>').select2({ data: options });Rhettrhetta
P
7

First empty the list then re-initialize it again

$quantitySelect.empty().select2();

https://jsfiddle.net/qum29ken/

Phototelegraphy answered 10/11, 2015 at 9:37 Comment(1)
This has no effect on select2 4.0.0Brigittebriley
H
0

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

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

Hovey answered 10/11, 2015 at 9:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.