How to open Bootstrap dropdown programmatically

后端 未结 16 1843
轮回少年
轮回少年 2020-12-01 13:56

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

相关标签:
16条回答
  • 2020-12-01 13:56

    dropdown('toggle') works great for me when using the button tag.

    JS

    $("#mybutton").dropdown('toggle')
    

    HTML

    <button class="dropdown-toggle ban" role="button" data-toggle="dropdown" data-target="#" id="mybutton">...</button>
    
    0 讨论(0)
  • 2020-12-01 13:58

    most of the time act as a manual action works :

    $('#sidebar_filter_city li').click(function(){   
        $('#sidebar_filter_areas').click();
    });
    
    0 讨论(0)
  • 2020-12-01 14:01

    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:

    • If you want to trigger it by clicking on another element, you must kill the click event on the other element- otherwise Bootstrap will treat it as a click outside of the dropdown and immediately close it.
    • $('.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

    0 讨论(0)
  • 2020-12-01 14:02

    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.

    0 讨论(0)
  • 2020-12-01 14:03

    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 :)

    0 讨论(0)
  • 2020-12-01 14:04

    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.

    0 讨论(0)
提交回复
热议问题