简体   繁体   中英

Show/Hide option in Select2 using toggle or similar

I have a drop-down element which I apply .select2() , before, when it's a common SELECT element I use this code to toggle a element:

$('#orders_nat_lives_in_ccs').click(function() {
    $(".shipping_from option[value='MRW']").toggle(!this.checked);
    $(".shipping_from option:eq(" + ((this.checked) ? 1 : 0) + ")").prop('selected', true);

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

But this not work for Select2 what's the right way to do this using this library?

Here you have a Fiddle example around what I'm talking about, first drop-down has .select2() applied and code doesn't work, second one is the same but without Select2 and the same code works.

As select to is taking options even if they are hidden I found removing and appending the option is easier. please find the code bellow

$('#orders_nat_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");

    }
//    $(".shipping_from option[value='MRW']").toggle(!this.checked);
//    $(".shipping_from option:eq(" + ((this.checked) ? 1 : 0) + ")").prop('selected', true);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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