Bujji
Bujji

Reputation: 1727

How to add Twitter Bootstrap dropdown items dynamically

I am adding drop down dynamically in java script using twitter bootstrap , but some how the drop down is not opening .

Below is the code and here is jsfiddle http://jsfiddle.net/szx4Y/281/

<div class="dropdown" >
    <a data-toggle="dropdown" class="downarrow dropdown-toggle" href="#">Dropdown V</a>
</div>

jQuery(document).ready(function() {
    $('.dropdown').on('click','a[data-toggle="dropdown"]', function(){   
        if($(this).children().length <= 0){
            $(this).append( '<ul class="dropdown-menu" role="menu" aria-labelledby="dLabel" >'+ '<li><a href="#">Edit</a></li><li><a href="#">Report</a></li><li><a href="#">Delete</a></li></ul>' );
            $(this).dropdown();
        }
    });              
});

Thanks for your help

Upvotes: 0

Views: 5527

Answers (1)

joshhunt
joshhunt

Reputation: 5335

Use jQuery's "after" method instead of "append". According to the Bootstrap markup you want .dropdown-menu to be next to the link/button, not inside of it. Full code:

jQuery(document).ready(function () {
    $('.dropdown').on('click', 'a[data-toggle="dropdown"]',
        function () {
            if ($(this).children().length <= 0) {
                $(this).after('<ul class="dropdown-menu" role="menu" aria-labelledby="dLabel" >' + '<li><a href="#">Edit</a></li><li><a href="#">Report</a></li><li><a href="#">Delete</a></li></ul>');
                $(this).dropdown('toggle');
            }
        });
});

JSFiddle

Upvotes: 3

Related Questions