I have the unordered list;
<ul id="names">
<li id="john"><div>data from database</div></li>
<li id="peter"><div>data from database</div></li>
<li id="mathhewm"><div>data from database</div></li>
<li id="philip"><div>data from database</div></li>
<li id="tarheoweh"><div>data from database</div></li>
</ul>
The list above is generated dynamically using ajax and jquery, that executes fine without a problem. The problem is that I want to get the ID of a list whenever a user click on any of them and I am currently using the code below which gives me on the ID of the first list element.
$(document).ready(function(){
$('#names').click(function(){
var name=$('#names li').attr('id');
alert(name);
});
The code above executes well but not not the output I want. I need any help, suggestion or criticism. Thanks and I appreciate.
try this:
$(document).ready(function(){
$('#names li').click(function(){
var name = this.id;
alert(name);
});
});
but you should create valid HTML! li
nested in li
is not valid
maybe this is better:
<ul id="names">
<li id="john"><div>data from database</div></li>
<li id="peter"><div>data from database</div></li>
<li id="mathhewm"><div>data from database</div></li>
<li id="philip"><div>data from database</div></li>
<li id="tarheoweh"><div>data from database</div></li>
</ul>
That html is not correct, you can place ul under li but cannot place li under li. Apart from that, if ul list is generated dynamically, you cannot use click event. Try "on" event instead.
$('#names').on('click', function(){
...
HTML:
<ul class="my-items" id="names">
<li id="john"><div>data from database</div></li>
<li id="peter"><div>data from database</div></li>
<li id="mathhewm"><div>data from database</div></li>
<li id="philip"><div>data from database</div></li>
<li id="tarheoweh"><div>data from database</div></li>
</ul>
jQuery delegate to attach one listener that catches all clicks on li
elements under id="names"
jQuery(function() {
jQuery(document).on('click', '#names li', function(e) {
var clickedLi = e.currentTarget.id;
});
})
Here is a jsFiddle with a working example.
Try this
$(document).ready(function(){
$('#names').click(function(){
$('#names li').each(function(){
alert($(this).attr('id'));
});
});
});