0

I have this fiddle that works nicely. So when I click on one of the list items in the menu I get an alert telling me which item was clicked.

However, in my actual application nothing happens when I click on a list item and to me, it looks exactly the same?


// get list of strategies
var $regions = $('#regionList');

$.ajax({
  type: 'GET',
  url: 'api/Region',
  dataType: 'json',
  success: function(codes) {
    $.each(codes, function(i, code) {
      $regions.append('<li id="' + code + '">' + code + '</li>');
    });
  },
  error: function() {
    alert("Error loading data! Please try again");
  }
});

$("#regionList li").click(function() {
  alert('Clicked ' + this.id);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<body>
  <div class="dropdown">
    <button class="dropbtn">Strategy</button>
    <div class="dropdown-content">
      <ul id="regionList"></ul>
    </div>
  </div>
Alex
  • 2,164
  • 1
  • 9
  • 27
mHelpMe
  • 6,336
  • 24
  • 75
  • 150
  • `api/Region`, is this a local or remote file? – Alex Jul 02 '18 at 15:45
  • 1
    You order a pizza, you hang up the phone and you try to eat it. The lis do not exist yet when you bind the event. Either put the click in the success call or you do event delegation. – epascarello Jul 02 '18 at 15:45
  • @epascarello wow lols, good spot. Move your event definition on `success`. – Alex Jul 02 '18 at 15:46

2 Answers2

1

Li elements are created dynamically. hence your way of attaching listener is not applicable for them. Attach your listener in following ways. it will work.

$(document).on('click',"#regionList li",function () {
    alert('Clicked ' + this.id);
});
Manoj
  • 1,175
  • 7
  • 11
0

I would bind the click event on the success of the ajax call otherwise you cannot be sure that the li are there