jquery – 根据其他列表中的选择禁用下拉列表中的选项

前端之家收集整理的这篇文章主要介绍了jquery – 根据其他列表中的选择禁用下拉列表中的选项前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有以下代码
  1. $('select').on('change',function(){
  2. $('select option').prop("disabled",false);
  3. $("select").not(this).find("option[value="+ $(this).val() + "]").prop('disabled',true);
  4. });

然后有3个下拉列表

  1. <select name="vote1" id="vote1">
  2. <option value="player1">Player1</option>
  3. <option value="player2">Player2</option>
  4. <option value="player3">Player3</option>
  5. <option value="player4">Player3</option>
  6. </select>
  7. <select name="vote2" id="vote2">
  8. <option value="player1">Player1</option>
  9. <option value="player2">Player2</option>
  10. <option value="player3">Player3</option>
  11. <option value="player4">Player3</option>
  12. </select>
  13. <select name="vote3" id="vote3">
  14. <option value="player1">Player1</option>
  15. <option value="player2">Player2</option>
  16. <option value="player3">Player3</option>
  17. <option value="player4">Player3</option>
  18. </select>

使用我的代码,当您选择1项时,它会在其他两个迭代的下拉列表中禁用它,但是如果我再单击另一个列表中的另一个选项,则会启用其他选项中的选项.

我希望能够在一个下拉列表中选择该选项,并在所有其他下拉列表中保持禁用状态,直到取消选中该选项.

这可能吗?

JS fiddle

解决方法

这与您已经拥有的几乎完全相同,除了每次更改时循环遍历每个选择,并禁用在其他选择中选择的选项:
  1. var $selects = $('select');
  2.  
  3. $selects.on('change',function() {
  4.  
  5. // enable all options
  6. $selects.find('option').prop('disabled',false);
  7.  
  8. // loop over each select,use its value to
  9. // disable the options in the other selects
  10. $selects.each(function() {
  11. $selects.not(this)
  12. .find('option[value="' + this.value + '"]')
  13. .prop('disabled',true);
  14. });
  15.  
  16. });

Here’s a fiddle

猜你在找的jQuery相关文章