Kalani Kalani - 1 year ago 76
CSS Question

Show dynamic nested dropdown lists in bootstrap

I am new to this so please bear with me ..

I have tried different solutions but i don't to get what I need working right. My list of data is read from a JSON file with this code

function showInsatserList() {
var promise = [];
promise = getSelectedSubareaInsatslist();
promise.done(function (insatserlist) {
$('#dropdownmenu li').remove();
for (var i in insatserlist) {
$('#dropdownmenu').append('<li class="dropdown-submenu"><a href="#">' + insatserlist[i].title + '</a> '
+ '<ul class="dropdown-menu"><li>HEJ</li></ul></li>');

and then i show it using this ..

$('.insatsDropdown').on('click', function (e) {

now my html look like this ...

<div class="dropdown insatsDropdown">
<a href="#" class="btn dropdown-toggle" data-toggle="dropdown">Välj insatser <span class="caret"></span></a>
<ul id="dropdownmenu" class="dropdown-menu"></ul>

What i want to do is that when i click on any of the li from the dropdown menu, it would show only the underlying submenu which at the moment is populated with just a randowm word in swedish "HEJ".

I tried standard click methods but the only thing that would work on dynamic content seems to be by using this line of code below ..

$(document).on('click', '.dropdown-submenu', function (e) {
$(this).find('ul').toggle(); //not working

the problem is that .. what i do inside does not really toggle anything

my fiddle is here :


What i want to do there now is that.. for example.. i click on one of the li.. like "Volvo".. it would show the underlying ul element.

I am open to different approaches too. I tried adding the ul element also when clicking but that does not work either yet for me.

Answer Source

You have to add some extra styles (code below) in order to show the nested lists on hover. See https://jsfiddle.net/yvrL24Lv/10/

.dropdown-submenu {
    position: relative;

.dropdown-submenu>.dropdown-menu {
    top: 0;
    left: 100%;
    margin-top: -6px;
    margin-left: -1px;
    -webkit-border-radius: 0 6px 6px 6px;
    -moz-border-radius: 0 6px 6px;
    border-radius: 0 6px 6px 6px;

.dropdown-submenu:hover>.dropdown-menu {
    display: block;

.dropdown-submenu>a:after {
    display: block;
    content: " ";
    float: right;
    width: 0;
    height: 0;
    border-color: transparent;
    border-style: solid;
    border-width: 5px 0 5px 5px;
    border-left-color: #ccc;
    margin-top: 5px;
    margin-right: -10px;

.dropdown-submenu:hover>a:after {
    border-left-color: #fff;

.dropdown-submenu.pull-left {
    float: none;

.dropdown-submenu.pull-left>.dropdown-menu {
    left: -100%;
    margin-left: 10px;
    -webkit-border-radius: 6px 0 6px 6px;
    -moz-border-radius: 6px 0 6px 6px;
    border-radius: 6px 0 6px 6px;