替换select2选项?

tom*_*ato 4 jquery jquery-select2

所有,

我有两个选择框:

  • 水果选择
  • FruitQuantity选择

根据Fruit中选择的选项,将影响FruitQuantity的选项.

所以使用select2,我想简单地通过这样做替换select中的所有选项.

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 });
Run Code Online (Sandbox Code Playgroud)

问题是select2只是将新数据附加到已经存在的内容上.我希望它清除所有选项并添加新选项.

否则我的选择框会填满不正确的选项.

我试过这个问题使用jQuery Select2清除下拉列表

$quantitySelect.select2('data', null)
Run Code Online (Sandbox Code Playgroud)

这没什么,但它不清楚.

帮助我欧比万,你是我唯一的希望.

Det*_*iel 9

假设您使用select2 4.0.0和以下类型的HTML:

<select id="fruits">
    <option value="apple" selected>Apples</option>
    <option value="pear">Pears</option>
</select>
<select id="quantities"></select>
Run Code Online (Sandbox Code Playgroud)

您需要"change""#fruits"控件上收听事件,并且每次更改时,您都需要"#quantities"使用相关数据重新填充下拉列表.

这是它的样子:

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();
Run Code Online (Sandbox Code Playgroud)

你可以在这个JSFiddle中看到这个


Ema*_*lil 6

首先清空列表然后重新初始化它

$quantitySelect.empty().select2();
Run Code Online (Sandbox Code Playgroud)

https://jsfiddle.net/qum29ken/