jQuery Chosen:如何选择1个选项值并在另一个选择菜单中删除相同的值?

Mar*_*out 9 jquery plugins select option jquery-chosen

我把2个元素放在彼此旁边.他们都使用jQuery Chosen插件.

这是代码:

<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>
Run Code Online (Sandbox Code Playgroud)

这是Javascript.jQuery库,最新的Chosen插件和CSS都包含在课程中.

<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>
Run Code Online (Sandbox Code Playgroud)

这是我想用上面的脚本完成的.

  • 有两个具有相同值的选择元素.例如,当在元素1中选择值"1"时,我想在元素2中禁用它.
  • 然而.在我取消选择元素1中的值"1"之后,它仍然在元素2中被禁用.这不是我想要的.取消选择第1个元素中的值后,应该再次使用另一个值.

有人知道怎么做到这一点吗?

编辑

现在我已经提出了一个的jsfiddle 正确的位置:http://jsfiddle.net/dq97z/3/.任何帮助将非常感激!

Dav*_*och 24

这样的事情应该这样做:

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");
});
Run Code Online (Sandbox Code Playgroud)

  • @DavidMurdoch谢谢你的剧本.对于更新版本,使用choices.trigger("selected:updated"); (2认同)