Philipp Schmid Philipp Schmid - 1 year ago 53
Ajax Question

Get ID of clicked <li>

I have a dropdown list of items:

<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Räume <span class="caret"></span></a>
<ul class="dropdown-menu" id="Room">
<!-- Auto-Generated: Dropdown content -->
</ul>


.. where the generated elements look like this:

<li class='LiRoom' id='Room 1'><a href='#'>R101</a></li>
<li class='LiRoom' id='Room 2'><a href='#'>R102</a></li>


.. and I want to display database entries on my website, depending on the selected
<li>
item's ID:

$(document).ready(function(){
$("#Room").click(function() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById('accordion').innerHTML = this.responseText;
}
};
xmlhttp.open("GET", "GetRoomComponents.php?q=1", true);
xmlhttp.send();
});
});


The
1
of
GetRoomComponents.php?q=1
needs to be replaced with the
<li>
's ID. But how do I access the correct one?

This answer https://stackoverflow.com/a/3545356/5790966 (replacing
"#Room"
with
"#Room li"
) didn't work. If I do that, the entire function doesn't execute (tested on the latest Chrome).

Answer Source

Firstly, you may as well use jQuery to make your AJAX request if you've already got it loaded; it's much simpler logic.

To address your issue, you can attach a delegated click() handler to all the li a elements, then use the this keyword to reference the one which raised the event. You can then read the prop('id') from the parent li. Try this:

$("#Room").on('click', 'li a', function(e) {
  e.preventDefault();
  var liId = $(this).closest('li').prop('id');
  $('#accordion').load('GetRoomComponents.php?q=' + liId);
});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download