0

I'm trying to get the data-id attribute after a click on the appropriate div. This is my html structure:

<div id="existing-risorse-list">
   <div data-id="30">Cabina Cb</div>
   <div data-id="32">Risorsa1 R1</div>
   <div data-id="33">Cabina2 Cb2</div>
</div>

Essentially when the user click on Cabina Cb I want return the id 30, this is my code:

$(document).on('click', '#existing-risorse-list div', function() 
{
    var this_id = $(this).attr('data-id');
    alert(this_id); 
});

the event is fired correctly but the alert return

undefined

What am I doing wrong?

2 Answers2

0

Demo

$("#existing-risorse-list div").on('click', function() 
{
    var this_id = $(this).attr('data-id');
    alert(this_id); 
});
Diptox
  • 1,809
  • 10
  • 19
0

@Diptox code works but isn't very performant, the original code in your question is a better way of doing it, as the event is on a single element. the issue maybe caused by you targeting $(document) a simple solution is to target #existing-risorse-list eg:

$("#existing-risorse-list").on('click','div', function() 
{
    var this_id = $(this).attr('data-id');
    alert(this_id); 
});

Hope that helps

Sam
  • 755
  • 4
  • 15
  • On a side note, it would be much better if the interactive elements, eg `
    ` could be focused via tabbing, this can be [achieved by adding a tabIndex] (http://stackoverflow.com/questions/3059203/tab-index-on-div) `
    ` or even better converting the `div`s to links `Cabina Cb` you could maybe then have a no js version?!?
    – Sam Oct 13 '15 at 11:13