Dynamically select Drop Down in Jquery

前端 未结 4 893
遇见更好的自我
遇见更好的自我 2021-01-29 09:16

I have 4 Drop Downs.

Each drop by default has a --select-- option. Each box has a unique id. As you can see, the second drop down is disabled if the above drop

4条回答
  •  一向
    一向 (楼主)
    2021-01-29 09:37

    Rather than hiding the options, I would use the disable attribute (comments in code):

    var selects = $('.drop-down');
    selects.not(':eq(0)').prop('disabled', true); // disable all but first drop down
    
    selects.on('change', function() {
      var select = $(this),
          currentIndex = selects.index(select),
          nextIndex = currentIndex + 1;
      
      // only do this if it is not last select
      if (currentIndex != selects.length - 1) { 
        selects.slice(nextIndex)        // get all selects after current one
               .val('')                 // reset value
               .prop('disabled', true); // disable 
        
        selects.eq(nextIndex).prop('disabled', select.val() === ''); // disable / enable next select based on val
      }
      
    })
    
    


提交回复
热议问题