简体   繁体   English

如何使用jQuery从选择元素中删除选项?

[英]How to remove options from select element using jquery?

I have n drop-downs like this: 我有n个这样的下拉菜单:

<select id="select1">
  <option>1</option>
  <option>2</option>
  <option>3</option>
</select>

<select id="select2">
 <option>1</option>
 <option>2</option>
 <option>3</option>
</select>

with identical options. 具有相同的选项。 All the choices should be unique, so once the option is selected in one combobox, it should be removed from others. 所有选项都应该是唯一的,因此一旦在一个组合框中选择了该选项,就应将其从其他组合中删除。 So, if a user selects "1" in select1 there will be only options "2" and "3" in select2. 因此,如果用户在select1中选择“ 1”,则select2中将只有选项“ 2”和“ 3”。

Now, jQuery disable SELECT options based on Radio selected (Need support for all browsers) offers a nice solution, but how can I modify this to work with selects instead of radio buttons? 现在, jQuery根据选定的Radio禁用SELECT选项(需要对所有浏览器的支持)提供了一个不错的解决方案,但是如何修改它以使用select而不是单选按钮呢?

Is this what you mean? 你是这个意思吗?

This would remove everything from #select2 that was in #select1 : 这将从#select1 #select2中删除所有内容:

$("#select2 option").each(function() {
    if($("#select1 option[value=" + this.value + "]").length)
        $(this).remove();
});

Here's another alternative that removes all duplicates: 这是删除所有重复项的另一种选择:

$("select").each(function() {
  var select = $(this);  
  select.children("option").each(function() {
    $('select').not(select).children("option[value=" + this.value + "]").remove();
  });
});

This removes every duplicate, leaving he option only in the first <select> it found it in.​ 这将删除所有重复项,仅在找到它的第一个<select>保留选项。

Update for your comment: 更新您的评论:

$("#select1").change(function() {
 $("#select2 option[value=" + $(this).val()+ "]").remove();
});

Alternatively, if the selects have the same options in the same order. 或者,如果选择具有相同顺序的相同选项。

$('select').change(function() {
    var selectedIndex = $(this).find(':selected').index();    
    $('select').not(this).find('option:nth-child(' + selectedIndex + ')').remove();
)};

I think this way is faster (but less easy to read). 我认为这种方式速度更快(但不易阅读)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM