0

I have filled some "ul"s directly in HTML e.g.

<button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">Kennzahl
    <span class="caret"></span></button>
        <ul class="dropdown-menu" id="measure">
            <li><a href="#">volume</a></li>
            <li><a href="#">netSentiment</a></li>
            <li><a href="#">authors</a></li>
        </ul>

and had no trouble reading the selected value by

$('#measure li').on('click', function(){
    $(this).text();
});

Then I have tried to get the chosen Value from a "ul" that I filled by JavaScript:

Something like

$('#projectId').append('<li><a href="#">' + projects[i].name + '</a></li>');

The Select is filled with the "li"s. But when I select one, the result isn't caught by the same JavaScript I could use with the "li" directly filled in HTML.

heckerf
  • 33
  • 1
  • 7

2 Answers2

0

When you dynamically add new elements after the page has loaded, you need to delegate the events to a parent element. You've almost done this, just change you code to

$('#measure').on('click','li', function(){
    $(this).text();
});

Note your method here will not do anything - but ive kept the code as close to your example. Perhaps you meant console.log($(this).text());

Jamiec
  • 133,658
  • 13
  • 134
  • 193
0

What you need is Binding for dynamically created elements

$('#measure').on('click', 'li', function(){
    alert($(this).text());
});

$('#measure').append('<li><a href="#">abc</a></li>');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

   
    <span class="caret"></span></button>
        <ul class="dropdown-menu" id="measure">
            <li><a href="#">volume</a></li>
            <li><a href="#">netSentiment</a></li>
            <li><a href="#">authors</a></li>
        </ul>

Here i have created abc li using jquery but still on clicking it, it gives alert just like other li.

Raj
  • 1,928
  • 3
  • 29
  • 53