Search code examples
javascripthtmlsalesforcedropdownhtml-select

How to Add/Remove select option from 1 drop down on selection of other dropdown option


Suppose I have 2 dropdowns. My requirement is, On selection of an option in first dropdown that option should be removed from other dropdown and on unselection of that option from the first dropdown that option should be available in other dropdown for selecion.


Solution

  • I have written the following JavaScript to solve above problem, just give your dropdowns a common class like "importance" here and use this code:

                var j$importance = j$(".importance");
    
                j$importance.on("change", function () {
    
                    var select = this,
                        selected = j$("option:selected", this).text();
    
                    var currentUnselectedValues = [];
    
                    j$('option', this).each(function() { 
    
                        currentUnselectedValues.push( j$(this).text());
                    });
    
                    j$importance.each(function (_, el) {
    
                        for(i=0; i<currentUnselectedValues.length; i++){
    
                           var exist = false;
    
                           j$('option', el).each(function(_, elm) { 
    
                               if(currentUnselectedValues[i] === j$(elm).text()){
    
                                   exist = true;
                               }
                           });
    
                           if(exist === false){
    
                              j$(el).append('<option value="' + currentUnselectedValues[i] + '">' + currentUnselectedValues[i] + '</option>');
                           }
                        }
    
                        if (el !== select) {
                            j$("option", el).each(function (_, el) {
                                var j$el = j$(el);
                                if (j$el.text() === selected && j$el.text() != '--None--') {
                                    j$el.remove();
                                }
                            });
                        }
                    });
    
                 });