Click on table row and get row ID/value

Hi all,

Really hoping someone can help me here. I am still a JS newbie and have been struggling with this for the last two days! This is for a mobile app built using Framework7.

I am dynamically building a html table with JSON data, and I am trying to get the row ID when a row of the table is clicked on. So far my code is as follows (I have included comments):

//Do something when button is clicked
$$('.page-content').find('#airconSearch').on('click', function (e) {  
  //Show preloader
  app.preloader.show();
  //Request JSON data
  app.request.json('my-URL', function (data) {
    var tableHtml = '';
      for(var i = 0; i < data.length; i+=1){
        //Use JSON data to give each row an ID and populate the 3 columns
        tableHtml+= '<tr id="' +data[i].am_5_regnumber+ '"><td class="numeric-only">' +data[i].brand+ '</td> <td class="numeric-only">' +data[i].model+ '</td> <td class="numeric-only">' +data[i].ac_31_eeclassc+ '</td></tr>';        
      }  
    //Add the columns to the html table  
    $$('.data-table #airconList').html(tableHtml);
    //Hide preloader after function is complete
    app.preloader.hide();
    //Do something when a table row is clicked
    $$('.data-table #airconList tr').on('click', e => {  
      //Get the clicked row ID
      var zaf = $$('.data-table #airconList tr').attr("id");
      //Log the ID to the console
      console.log(zaf);        
    })  
  })          
}) 

The dynamic table builds with no issues and the console shows that each row has an ID:

image

However when I click on any row in the table, the console keeps logging the ID for the first row. Does anyone have a possible for solution for this? I am not sure if I need some sort of loop but I am not winning unfortunately.

Thanks

Framework7 utilizes it’s own DOM manipulation called DOM7 so $$ is used to prevent conflicts with other libraries (such as jQuery).

var zaf = $$('.data-table #airconList tr');
console.log(zaf);  

Logs “DOM7” to the console with all of the different manipulation options:

image

I was hoping using “closest” would help but the console keeps logging the ID for the first row only :thinking:

var zaf = $$('.data-table #airconList tr').closest('.data-table tr').attr("id");

I really appreciate you being so willing to help, but I managed to get it working this morning.

I decided to firstly simplify the table and get it working with Jquery. You can try out the simple JSfiddle here, but basically it uses:

$(document).on("click", "#animals tbody tr", function() {
  var animal = $(this).closest('tr').attr('id');
  alert("I am a " + animal);
});

Once this was working, I adapted it to my Framework7 project:

$$('.data-table #airconList tbody tr').on('click', function (e) {
  var zaf = $$(this).closest('tr').attr('id');
  console.log(zaf);        
})