简体   繁体   English

从Select2删除项目不起作用

[英]Remove item from Select2 is not working

I have a drop-down (select) to which I apply a .select2() . 我有一个下拉列表(选择),我在其中应用了.select2() Now I'm trying to remove/add a option from the drop-down by mark/unmark a checkbox and it's not working. 现在,我试图通过标记/取消标记复选框来从下拉列表中删除/添加选项,但它不起作用。 This is the HTML code: 这是HTML代码:

<input type="checkbox" value="1" class="lives_in_css" name="orders[lives_in_ccs]" id="orders_lives_in_ccs">

<select class="shipping_from form-control toSelect2 select2-offscreen" required="required" name="orders[shipping_from]" id="orders_shipping_from" tabindex="-1" title="" data-bv-field="orders[shipping_from]">
    <option selected="selected" value="">-- SELECCIONAR --</option>
    <option value="MRW">MRW - COBRO EN DESTINO</option>
    <option value="DOMESA">DOMESA - COBRO EN DESTINO</option>
    <option value="ZOOM">GRUPO ZOOM - COBRO EN DESTINO</option>
</select>

And this is the jQuery code I made for this purpose: 这是我为此目的制作的jQuery代码:

$('.lives_in_ccs').click(function() {
    if (this.checked) {
        $(".shipping_from option[value='MRW']").remove();
        $(".shipping_from").select2("val", "DOMESA");
    } else {
        $(".shipping_from").prepend('<option value="MRW">MRW - COBRO EN DESTINO</option>');
        $(".shipping_from").select2("val", "MRW");
    }

    console.log(this.checked);

    $(".secure_shipping").toggle(this.checked);
});

What's wrong in my code? 我的代码有什么问题? Here is jsFiddle to play with 是jsFiddle可以玩的

You are looking to detach the given list item, and then reattach it when the checkbox is unchecked? 您是否要分离给定的列表项,然后在取消选中该复选框时重新附加它? I am unfamiliar with select2, but the following does that: 我不熟悉select2,但是以下操作可以做到这一点:

$(document).ready(function () {
    $('.toSelect2').select2();
    var detachedMember;
    $('.lives_in_css').click(function () {
        if (this.checked) {
            detachedMember = $('option[value="MRW"]').detach();
        } else {
            $('option[value=""]').after(detachedMember);
        }
        $(".secure_shipping").toggle(this.checked);
    });
});

Here's a fiddle 这是一个小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM