dante dante - 4 months ago 15
Javascript Question

Disable options already selected in another multiple select box

I have seen this working with a single select box, but couldn't manage to do it with multiple select boxes.

Let's say i have two multiple selects:

<select class='test' multiple>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>

<select class='test' multiple>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>


How can I manage to lock the option audi if selected in any of the select boxes?

I was trying using:

$(document).on('change', function(e) {
e.preventDefault();
$('.test').find('option').prop('disabled', false);
$('.test').each(function() {
$('.test').not(this).find('option[value="' + this.value + '"]').prop('disabled', true);
});
});

Answer

You need to save the value and pass it to the other option. Like this:

 $('.test').on('change', function() {
    var selected = $(this).children(':selected').val();
    $('.test').val(selected);
 });

http://codepen.io/sandrina-p/pen/KrZRXj

  • EDIT - i changed it to accept an array of values

    $('.test').on('change', function() {
        var selected = $(this).val();
        $('.test').val(selected);
    });
    
Comments