CY5
CY5

Reputation: 113

How to get data-attr when click table row

I have table and I want to get a data attribute of column "geometry" of the row which is clicked. So what I am doing is:

var row = jQuery(this).closest("tr");  

Above code is to get that row which is clicked and the below code is to get data attribute from column geometry, my data attribute is data-geomet.

var text = row.find("geometry").data("geomet");
console.log(text);

I am getting text undefined. I get text() of class geometry but could not get data attribute.

Example HTML:

<td class="geometry" data-geomet="${obj["Details"]}"> details["geometry"]</td></tr>

UPDATE

    %for obj in tableData:
        var details=JSON.parse('${obj["Details"]}');
        var data = "<tr><td> <a href='#gMap' class='fence_data'>${obj['Geofence_Name']}</a></td>";
        data += "<td>${obj['Vehicle_Id']}</td>";
        if(details["type"]===undefined){
            data += '<td>NA</td>';  
        }
        else{
            data += '<td class="type"> '+details["type"]+'</td>';
        }
        if(details["radius"]===undefined){
            data += '<td>NA</td>';  
        }
        else{
            data+='<td class="radius"> '+details["radius"]+'</td>';
        }
        if(details["geometry"]===undefined){
            data += '<td>NA</td></tr>'; 
        }
        else{
            data += '<td class="geometry" data-geomet="${obj["Details"]}"> '+details["geometry"]+'</td></tr>';
        }
       table.append(data)

    %endfor

Here is an example jsfiddle.net/3vmL5277/2 where I am getting undefined.

Upvotes: 4

Views: 15103

Answers (2)

faerin
faerin

Reputation: 1925

Without knowing what your HTML markup looks like, here's something assuming that your accurate tds are attached to a class called 'geometry':

$('.geometry').on('click',function(){
   var myDataAttr = $(this).data('geomet');
   console.log(myDataAttr);
   });

Fiddle: http://jsfiddle.net/3vmL5277/

EDIT: Here's a new example according to your comment:

$('tr').on('click',function(){
   var myDataAttr = $(this).find('td.geometry').data('geomet');
   console.log(myDataAttr);
   });

http://jsfiddle.net/3vmL5277/3/

Upvotes: 1

Rory McCrossan
Rory McCrossan

Reputation: 337580

Given your HTML in this format:

<td class="geometry" data-geomet="${obj["Details"]}"> details["geometry"]</td></tr>

This code should work for you:

// assuming this code is in an event handler
// and 'this' refers to an element within a 'tr' element
var $row = jQuery(this).closest("tr");
var text = $row.find(".geometry").data("geomet");
console.log(text);

Upvotes: 3

Related Questions