Kalani Kalani - 1 year ago 43
jQuery Question

How to display ONLY the ul submenu when parent li is clicked?

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.


You just have to load jQuery before bootstrap. Isn't this right? https://jsfiddle.net/yvrL24Lv/2/

Also, I changed the code a bit so that showInsatserList(); runs (adds the items) only once, not on every click.

  $(function() {


  function showInsatserList() {
    var cars = ["Volvo", "BMW", "Renault"];
    for (var i in cars) {
      $('#dropdownmenu').append('<li class="dropdown-submenu"><a href="#">' + cars[i] + '</a> ' + '<ul class="dropdown-menu"><li>HEJ</li></ul></li>');