How to open Bootstrap dropdown programmatically

后端 未结 16 1925
轮回少年
轮回少年 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 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:



    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

提交回复
热议问题