MAX POWER
MAX POWER

Reputation: 5458

jQuery - prevent option deselect in select multiple

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?

Upvotes: 3

Views: 1612

Answers (3)

Caco
Caco

Reputation: 1654

Try this:

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

Upvotes: 0

adeneo
adeneo

Reputation: 318342

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

Upvotes: 1

celerno
celerno

Reputation: 1387

already tried this?:

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

Upvotes: 0

Related Questions