Chris Chris - 2 months ago 6
HTML Question

How to close bootstrap dropdown menu on button click?

I have a bootstrap dropdown menu that I open and got it staying open while I work with a grid that I placed inside of it, I can close the dropdown when I click outside of the dropdown area, but I want to close it down on a button click event..

Here is my html for the dropdown

<div class="dropdown">
<button class="btn dropdown-toggle col-md-3" type="button" data-toggle="dropdown">
Select Category
<span class="caret"></span>
</button>
<ul class="dropdown-menu col-md-7" onClick="event.stopPropagation();">
<div id="MaterialGridList" style="height:440px;"></div>
<button type="button" id="btnFilter" class="btn btn-sm btn-success">Filter</button>
</ul>
</div>


as you can see on the onClick event of the dropdown menu, it keeps it open. So what I would like to do is close it on the btnFilter click event.
Any idea's?

Answer

You can use the toggle function on the .dropdown that has the button inside:

$('#btnFilter').click(function() {
  $(this).parents('.dropdown').find('button.dropdown-toggle').dropdown('toggle')
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" />
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
<div class="dropdown">
    <button class="btn dropdown-toggle col-md-3" type="button" data-toggle="dropdown">
        Select Category
        <span class="caret"></span>
    </button>
    <ul class="dropdown-menu col-md-7" onClick="event.stopPropagation();">
        <div id="MaterialGridList" style="height:440px;"></div>
        <button type="button" id="btnFilter" class="btn btn-sm btn-success">Filter</button>
    </ul>
</div>

Comments