Search code examples
jqueryperformancedropdowncoding-efficiencypardot

how to make Jq script on Pardot shorten and more efficient


I wrote this code to make a dropdown menu set a class value on selection in order to know what I selected to make it red when a selection is required.

The thing is that it is Pardot and I can't change the HTML. this is what I have a (the class was set by me)

p.Environment select option 

The class changes for each dropdown The value is a number set by Pardot

any chance I can make this code just one function to work for all 3 dropdown but recognizing the dropdown I click?

<script>
// ---------Environment Dropdown Error-----------
(function() {
var selectedOption = 'option815221';
var drop = '.Environment';
$(drop).addClass(selectedOption);
$(drop+' select').change(function(){
    $(drop).removeClass(selectedOption).addClass("option"+$(this).val());
    selectedOption = "option"+$(this).val();
});
})();
// ---------Country Dropdown Error-----------
(function() {
var selectedOption = 'option815237';
var drop = '.country';
$(drop).addClass(selectedOption);
$(drop+' select').change(function(){
    $(drop).removeClass(selectedOption).addClass("option"+$(this).val());
    selectedOption = "option"+$(this).val();
});
})();
// ---------State Dropdown Error-----------
(function() {
var selectedOption = 'option824913';
var drop = '.state';
$(drop).addClass(selectedOption);
$(drop+' select').change(function(){
    $(drop).removeClass(selectedOption).addClass("option"+$(this).val());
    selectedOption = "option"+$(this).val();
});
})();
</script>

Solution

  • Something like this oughta do the trick.

    var optionsAndDrops = [
      ["option815221", ".Environment"],
      ["option815237", ".country"],
      ["option824913", ".state"],
    ];
    optionsAndDrops.forEach(([selectedOption, drop]) => {
      $(drop).addClass(selectedOption);
      $(drop + " select").change(function() {
        $(drop)
          .removeClass(selectedOption)
          .addClass("option" + $(this).val());
        selectedOption = "option" + $(this).val();
      });
    });
    

    EDIT: Or, more clearly perhaps, wrapping the logic in a real named function and just calling it thrice:

    function setupDropdown(drop, selectedOption) {
      $(drop).addClass(selectedOption);
      $(drop + " select").change(function() {
        $(drop)
          .removeClass(selectedOption)
          .addClass("option" + $(this).val());
        selectedOption = "option" + $(this).val();
      });
    }
    
    setupDropdown(".Environment", "option815221");
    setupDropdown(".country", "option815237");
    setupDropdown(".state", "option824913");