How to change the width of the dropdown using Bootstrap Multiselect plugin for jQuery?

bart picture bart · Jul 8, 2015 · Viewed 8.4k times · Source

I'm using David Sutz's bootstrap multiselect and I can't find a way to modify the .dropdown-menu on onDropdownShow. Setting the width in the function below does not work:

$('#flavor').multiselect({
    onDropdownShow: function(event) {
        $(this).closest('.dropdown-menu').css('width','500px')
    }
});

The problem lays in the $(this) which does not seem to be a DOM node, although I expect it to #flavor.

What I'm trying to do is dynamically change the menu's width depending on the window's width (basically making it responsive), so the code needs to be executed every time the menu is being opened. Additionally I have multiple multiselect boxes on my page, so it really needs to be a generic function without hard coded DOM references, hence the need for $(this) to work.

Answer

stevenw00 picture stevenw00 · Jul 10, 2015

You can use the event to find out which button was clicked. From there you can use simple jQuery traversal to find and edit the dropdown menu.

To have different behaviour based on which dropdown was opened, it is possible to target the id of the original select. Then probably using another function to return any changes required.

$(document).ready(function() {
  $('.dropdowns').multiselect({
    onDropdownShow: function(event) {
      var menu = $(event.currentTarget).find(".dropdown-menu");
      var original = $(event.currentTarget).prev("select").attr("id");
     
      // Custom functions here based on original select id
      if (original === "flavour") menu.css("width", 500);
      if (original === "flavour2") menu.css("background", "red");
      
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script src="https://raw.githubusercontent.com/davidstutz/bootstrap-multiselect/master/dist/js/bootstrap-multiselect.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">

<select id="flavour" class="dropdowns" multiple="multiple">
  <option value="cheese">Cheese</option>
  <option value="tomatoes">Tomatoes</option>
  <option value="mozarella">Mozzarella</option>
  <option value="mushrooms">Mushrooms</option>
  <option value="pepperoni">Pepperoni</option>
  <option value="onions">Onions</option>
</select>

<select id="flavour2" class="dropdowns" multiple="multiple">
  <option value="cheese">Cheese</option>
  <option value="tomatoes">Tomatoes</option>
  <option value="mozarella">Mozzarella</option>
  <option value="mushrooms">Mushrooms</option>
  <option value="pepperoni">Pepperoni</option>
  <option value="onions">Onions</option>
</select>

I couldn't find a CDN that hosted the plugin's css so the style will look a little different, but the JS code above works.