Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - prevent option deselect in select multiple

Tags:

jquery

Is it possible to prevent an option from being deselected in a select multiple control? Also it must not deselect any other selected options. I have tried:

$('#selections option').click(function(){
    $(this).prop('selected', true);
});

Doesn't seem to work. Anyone know how I can achieve this?

like image 923
MAX POWER Avatar asked Jun 22 '26 21:06

MAX POWER


1 Answers

Here's one way to do it

$('#selections').on('change', function(e) {
    var self = this,
        selected = $(this).data('selected') || [];

    $.each(selected, function(_,i) {
        $('option', self).eq(i).prop('selected', true)
    });

    $(this).data('selected', $.map($('option:selected', this), function(el) {
        return $(el).index();
    }));
});

FIDDLE

like image 152
adeneo Avatar answered Jun 24 '26 11:06

adeneo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!