更改中的jQuery仅显示所选选项,删除/禁用其余选项

时间:2015-01-27 01:29:20

标签: javascript jquery html select onchange

目标:从选择下拉菜单中,如果有人选择了某个选项,请在该下拉菜单中禁用/删除/隐藏其余选项。

这是下拉菜单。如果有人选择“1”,其余选项(2,3,4)将被删除/禁用/隐藏:

<div class="abc">
  <div class="xyz">
    <select name="pqr" class="selectDropdown">
      <option value='1'>1</option>
      <option value='2'>2</option>
      <option value='3'>3</option>
      <option value='4'>4</option>
    </select>
  </div>
</div>

以下是我尝试使用的JavaScript:

$('.selectDropdown').on('change', function(e) {
    $(this).closest('.abc').children('.xyz').children('option:not(:selected)').prop('disabled', true);
});

我知道,这里的JavaScript有问题。我在哪里弄错了?

4 个答案:

答案 0 :(得分:3)

保持简单并使用:

$('.selectDropdown').on('change', function(e) {
    $(this).children('option:not(:selected)').prop('disabled', true);
});

在此上下文中,$(this)表示.selectDropdownoption元素是孩子。

Example Here


..如果你想删除未选中的孩子:

$('.selectDropdown').on('change', function(e) {
    $(this).children('option:not(:selected)').remove();
});

Example Here


您的代码无法正常工作的原因是因为option元素是不是 .xyz元素的直接子元素。您将不得不使用:

$('.selectDropdown').on('change', function(e) {
    $(this).closest('.abc').children('.xyz').children().children('option:not(:selected)').prop('disabled', true);
});

(我只是在.children()之后链接了另一个.children('.xyz')方法。)

答案 1 :(得分:2)

你过度复杂化了。一旦用户点击了选择框,您就可以进入该选择器,这样就无需进入.abc和.xyz。

这是表明它在行动中的小提琴: http://jsfiddle.net/releaf/ng50zmyo/

$('.selectDropdown').on('change', function(e) {
 $(this).find('option:not(:selected)').prop('disabled', true);
});

答案 2 :(得分:1)

这简化了事情。由于thisselect,因此无需遍历2个级别并返回以重新开始重新开始的位置

$('.selectDropdown').on('change', function(e) {
    $(this).children(':not(:selected)').prop('disabled', true);
});

如果首选移除,则替换prop()

remove()

$('.selectDropdown').on('change', function(e) {
    $(this).children(':not(:selected)').prop('disabled', true);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="abc">
  <div class="xyz">
    <select name="pqr" class="selectDropdown">
      <option value='1'>1</option>
      <option value='2'>2</option>
      <option value='3'>3</option>
      <option value='4'>4</option>
    </select>
  </div>
</div>

答案 3 :(得分:0)

您只需选择错误的节点。 $(this).closest('.abc').children('.xyz') - &gt;此节点的子节点指向select,它没有子节点option

你走了:

$('.selectDropdown').on('change', function(e) {
    $('select[name="pqr"]').children('option:not(:selected)').prop('disabled', true);
});

JSFiddle