0

If I hardcode the data for a dropdown then I am able to get the dropdown selection showing using my code below:

HTML

<div class="btn-group" role="group">
    <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
        <span id="make-selected">Make</span> <span class="caret"></span>
    </button>
    <ul class="dropdown-menu" id="make-dropdown">
        <li><a href="#">Oldsmobile</a></li>
        <li><a href="#">Ford</a></li>
        <li><a href="#">Volkswagen</a></li>
        <li><a href="#">Chrysler</a></li>
        <li><a href="#">Pontiac</a></li>
    </ul>
</div>

JS

$('.dropdown-menu a').click(function(){
    $('#make-selected').text($(this).text());
});

My issue is if I am loading my data from another source then it no longer shows the selection as shown below.

// the input for this is just a JSON file.
function populateDropdown(jsonData) {
    for (var m in jsonData) {
        $('#make-dropdown').append('<li><a href="#" data-maker="' + jsonData[m] + '">' + jsonData[m] + '</a></li>')
    }
}

$('.dropdown-menu a').click(function(){
    $('#make-selected').text($(this).text());
    console.log("CLICKED" + this);
});

The dropdown list gets populated but once I click the selection nothing happens.

Joey
  • 1,724
  • 3
  • 18
  • 38
  • 1
    You need to use a delegated event handler as the content does not exist when the page loads. See the question I marked as duplicate for more information – Rory McCrossan Jan 05 '17 at 17:34
  • thanks @RoryMcCrossan. I tried searching but I guess I didn't really know what exactly to search for. This solved it! – Joey Jan 05 '17 at 17:42
  • Your "this" is the wrong context. Try ``$('.dropdown-menu a').click(function(e){ $('#make-selected').text($(e.currentTarget).text()); });`` – Josh Hibschman Jan 05 '17 at 17:44

0 Answers0