I\'m trying to open a Bootstrap dropdown when I click a item of another dropdown.
The idea is to select a city from the first drop down - then the script will auto o
dropdown('toggle')
works great for me when using the button tag.
$("#mybutton").dropdown('toggle')
<button class="dropdown-toggle ban" role="button" data-toggle="dropdown" data-target="#" id="mybutton">...</button>
most of the time act as a manual action works :
$('#sidebar_filter_city li').click(function(){
$('#sidebar_filter_areas').click();
});
The best way is to check if the dropdown is not already open, and then to use .dropdown('toggle')
.
Couple things to be aware of:
$('.dropdown').addClass('open')
is not a good replacement for
$('.dropdown-toggle').dropdown('toggle')
as suggested in other
answers, because it will cause the dropdown to stay permanently open
instead of closing when you click off of the component.HTML:
<button class="btn btn-secondary trigger_button">Trigger dropdown</button><br><br>
<div class="dropdown">
<button class="btn btn-secondary dropdown-toggle" type="button" data-toggle="dropdown">
Dropdown
</button>
<div class="dropdown-menu">
Stuff...
</div>
</div>
JS:
$('.trigger_button').click(function(e){
// Kill click event:
e.stopPropagation();
// Toggle dropdown if not already visible:
if ($('.dropdown').find('.dropdown-menu').is(":hidden")){
$('.dropdown-toggle').dropdown('toggle');
}
});
Fiddle example
Bootstrap's dropdown plugin waits for 'click.bs.dropdown' event to show the menu, so in this case:
$('#sidebar_filter_areas').trigger('click.bs.dropdown');
should work. This will not trigger other 'click' events on same element if any.
just use .click()
on data-toggle element
but do not forget e.stopPropagation()
these one simple line took me for hours, hope it's help :)
Something I like to use that has a bit more user-expected behavior:
if(!$('#myDropdown').hasClass('show')){
$('#myDropdown').dropdown('toggle');
}
If it is already open, don't do anything. If it is closed, then it should open.