So, I have this HTML code:
<input type="checkbox" id="orders_lives_in_ccs" name="orders[lives_in_ccs]" class="lives_in_ccs">
<select id="orders_shipping_from" name="orders[shipping_from]" required="required" class="shipping_from toSelect2">
<option value="" selected="selected">-- 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>
I need to remove the option MRW
when checkbox .lives_in_ccs
is checked so I made this code:
$(function () {
$('.toSelect2').select2();
var detachedMember;
$('.lives_in_ccs').click(function () {
if (this.checked) {
detachedMember = $('.shipping_from option[value="MRW"]').detach();
} else {
$('.shipping_from option[value=""]').after(detachedMember);
}
$(".secure_shipping").toggle(this.checked);
});
});
This code works but I'm having a problem and didn't found the way to fixit. Having this jsFiddle do this tests:
- Leave the SELECT with the default value which is
--SELECCIONAR--
and mark the check in the left side, that will works and will remove the optionMRW
from the main SELECT, if you unmark the check the value will appear again on the SELECT - Choose
MRW
(the first choice) on the SELECT and mark the check in the left side, that will remove the optionMRW
from the main SELECT, but will leave the option as SELECTED which is wrong since the server side isn't expecting it.
So, how do I remove the option even if it's selected on the SELECT element? Any help?
--SELECCIONAR--
. I think there is a method in Select2 that allows you to change the selected value. I think it isval
, but can't remember. – Toadfish