jQuery <select> option disabled if selected in other <select>

前端 未结 4 844
天命终不由人
天命终不由人 2020-12-13 08:20

I am trying to attempt to disable an option if it is selected in any of the selects

So for example if name=\"select1\" has selected option \"Test 2\", then I want \

4条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-13 08:25

    The problem with your code is that within the change() routine, you are looking at all of the selects, rather than the one that has changed and disabling all of the selected entries. You need to find the value of the selected entry in question and disable that in other selects, not the current one.

    Something like this may be of use [untested]:

    $(document).ready(function() {
      $("select").each(function(cSelect) {
        $(this).data('stored-value', $(this).val());
      });
    
      $("select").change(function() {
        var cSelected = $(this).val();
        var cPrevious = $(this).data('stored-value');
        $(this).data('stored-value', cSelected);
    
        var otherSelects = $("select").not(this);
    
        otherSelects.find('option[value=' + cPrevious + ']').removeAttr('disabled');
        otherSelects.find('option[value=' + cSelected + ']').attr('disabled', 'disabled');
      });
    });
    

    The stored-value bit is so you know which options to enable in other

    提交评论

提交回复
热议问题