Reputation: 18660
I have a drop-down (select) to which I apply a .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:
<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:
$('.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
Upvotes: 1
Views: 1594
Reputation: 4676
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:
$(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
Upvotes: 4