Skip to content Skip to sidebar Skip to footer

Bootstrap Dropdown Closing When Clicked

I put a form inside a bootstrap dropdown, but when I click any of the fields in the form, the dropdown goes away. I have this piece of code but I don't know where to put it to prev

Solution 1:

You can omit the dropdown call all together, the bootstrap dropdown works without it. Make sure you're wrapping your script properly, you can include it on the header or body of your page, although personally i prefer placing it on the body of your page.

JS

<scripttype="text/javascript">
    $('.dropdown-menu input, .dropdown-menu label').click(function(e) {
        e.stopPropagation();
    });
</script>

Solution 2:

If you want to stop closing only some of dropdown menu, not all of them, then just add an additional class to your ul block:

<ul class="dropdown-menu keep-open-on-click">

And use this code:

$(document).on('click', '.dropdown-menu', function(e) {
    if ($(this).hasClass('keep-open-on-click')) { e.stopPropagation(); }
});

Solution 3:

Time passed since answer had been accepted, but if you want to keep the dropdown opened, if it acts like a kind of dialog, the best way i think is:

$('.dropdown').dropdown().on("hide.bs.dropdown", function(e) {
            if ($.contains(dropdown, e.target)) {
                e.preventDefault();
            //or return false;
            }
        });

Solution 4:

You need to stop event from bubbling up the DOM tree:

$('.dropdown-menu').click(function(e) {
    e.stopPropagation();
});

event.stopPropagation prevents event from reaching the node where it's eventually handled by Bootstrap hiding menu.

Solution 5:

This works for my (lateral sidebar opening a simple link with bootstrap toggle)

$('.dropdown').find("a").not('.dropdown-toggle').on("click",function(e){
    e.stopImmediatePropagation();
});

Post a Comment for "Bootstrap Dropdown Closing When Clicked"