Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Chosen: how to select 1 option value and remove the same one in another select-menu?

I've put 2 elements next to eachother. Both of them are using the jQuery Chosen plugin.

This is the code:

<div class="wrapper">
  <select data-placeholder="Number row 1" style="width:350px;" multiple class="chzn-select">
    <option value=""></option>
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
    <option value="5">5</option>
    <option value="6">6</option>
  </select>

  <select data-placeholder="Number row 2" style="width:350px;" multiple class="chzn-select">
    <option value=""></option>
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
    <option value="5">5</option>
    <option value="6">6</option>
  </select>
</div>

This is the Javascript. jQuery library, the latest Chosen plugin and CSS are all properly included ofcourse.

<script>
$('.chzn-select').trigger("liszt:updated");
$('.chzn-select').chosen().change( function() {
  var selectedValue = $(this).find('option:selected').val();
  $(this).parent().find('option[value="'+ selectedValue +'"]:not(:selected)').attr('disabled','disabled');
});
</script>

This is what I want to accomplish with the script above.

  • There are two select elements with the same values. When value "1" has been selected in element 1 for example, I want to disable it in element 2.
  • However. after I deselect value "1" in element 1, it's still disabled in element 2. That's not what I want. The other value should be available again after deselecting the value in the 1st element.

Does anybody know how to accomplish this?

EDIT

I've now put up a JSFiddle right here: http://jsfiddle.net/dq97z/3/. Any help would be much appreciated!

like image 817
Martijn van Turnhout Avatar asked Feb 07 '12 18:02

Martijn van Turnhout


1 Answers

Something like this should do it:

http://jsfiddle.net/musicisair/dq97z/10/

// cache selects for use later
var selects = $('.chzn-select');

// whenever the selection changes, either disable or enable the 
// option in the other selects
selects.chosen().change(function() {
    var selected = [];

    // add all selected options to the array in the first loop
    selects.find("option").each(function() {
        if (this.selected) {
            selected[this.value] = this;
        }
    })

    // then either disabled or enable them in the second loop:
    .each(function() {

        // if the current option is already selected in another select disable it.
        // otherwise, enable it.
        this.disabled = selected[this.value] && selected[this.value] !== this;
    });

    // trigger the change in the "chosen" selects
    selects.trigger("liszt:updated");
});
like image 101
David Murdoch Avatar answered Sep 30 '22 20:09

David Murdoch