无法禁用已选择的相同选项

时间:2019-01-28 15:37:17

标签: javascript jquery

假设我有两个select。我正在尝试禁用类criterias中可用的选择之一中已经选择的选项,为此,我编写了以下代码,但没有用,我做错了什么?

$('.criterias').on('change', function(event) {
  var id = $(event.target).val();
  $('#container').find('.criterias')
    .siblings('.criterias')
    .children('option[value=' + id + ']')
    .attr('disabled', true)
    .siblings().removeAttr('disabled');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container">
  <table>
     <tr> 
        <td>
            <select class="criterias form-control">
              <option value="11">test1'</option>
              <option value="12">test2</option>
              <option value="13">test3</option>
            </select>
        </td>
      </tr>
      <tr> 
        <td>
            <select class="criterias form-control">
              <option value="11">test1'</option>
              <option value="12">test2</option>
              <option value="13">test3</option>
            </select>
        </td>
      </tr>
 </table>

1 个答案:

答案 0 :(得分:1)

要达到预期效果,请删除同级方法

$('.criterias').on('change', function(event) {
  var id = $(event.target).val();
  $('#container').find('.criterias')
    .children('option[value=' + id + ']')
    .attr('disabled', true)
    .siblings().removeAttr('disabled');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container">
  <div id="container">
  <table>
     <tr> 
        <td>
            <select class="criterias form-control">
              <option value="11">test1'</option>
              <option value="12">test2</option>
              <option value="13">test3</option>
            </select>
        </td>
      </tr>
      <tr> 
        <td>
            <select class="criterias form-control">
              <option value="11">test1'</option>
              <option value="12">test2</option>
              <option value="13">test3</option>
            </select>
        </td>
      </tr>
 </table>
</div>

codepen-https://codepen.io/nagasai/pen/daXVLr