I have a table that contains multiple dropdown menus for a list of profile images. I’ve tagged the list element with the DB id of the photo so I can perform the associated action. I’ve coded my table to look like this:
<table class="table table-bordered">
<tbody>
<tr>
<td><img src="/photos/files/5/m/131309a4fb918110ed1061e90a715eca.jpeg"/></td><td><div class="btn-group">
<a class="btn btn-primary" href="#"><i class="icon-user icon-white"></i> User</a>
<a class="btn btn-primary dropdown-toggle" data-toggle="dropdown" href="#"><span class="caret"></span></a>
<ul class="dropdown-menu">
<li id="5"><a href="#"><i class="icon-pencil"></i> Edit</a></li>
<li id="5"><a href="#"><i class="icon-trash"></i> Delete</a></li>
</ul>
</div>
</tr>
<tr>
<td><img src="/photos/files/5/m/b19102d8ba1158e2a139ffa84e8e8540.jpeg"/></td><td><div class="btn-group">
<a class="btn btn-primary" href="#"><i class="icon-user icon-white"></i> User</a>
<a class="btn btn-primary dropdown-toggle" data-toggle="dropdown" href="#"><span class="caret"></span></a>
<ul class="dropdown-menu">
<li id="7"><a href="#"><i class="icon-pencil"></i> Edit</a></li>
<li id="7"><a href="#"><i class="icon-trash"></i> Delete</a></li>
</ul>
</div></tr>
</tbody>
</table>
My jquery attempt is below but isn’t working:
$('.dropdown-menu').on('click', 'li', function(e){
if ($(this).attr('class')=='icon-pencil') {
var id = $(this).attr('id');
alert("ID= " + id);
}
});
I never hit my alert code so what am I missing here?
Also is there a better way to track the photo ID’s or will they work this way?
You have li > a > .icon-pencil in your structure but you’re looking for this.className on li click (which is, obviously, the li). Try this:
A cleaner approach would be to listen for click on the anchor, since this is the usual click element:
And the cleanest solution would be to set the ID’s only on .dropdown-menu, so they are unique, then get it via .closest(‘ul’) instead of .closest(‘li’).
PS: having duplicate IDs is always bad.