Khkhy Khkhy - 7 months ago 63
Javascript Question

How to get attribute value from table row on click

I have a TABLE which is empty. I have an array called menu which contains a list of some products.
The code below iterates menu and creates rows in the table as many as there is products in the menu array.

To identify products in rows, -the best approache I could think of, was to use attribute; data-ID="" to store id of the product which is inserted in the row.

var id=[];
$(document).ready(function addMenuToTable() {
for ( var i in menu) {
$('#menutable').append('<tr class ="product" role="button" data-id=""><td class"num">'+menu[i].num+'</td><td class="td-width"><span><b>'+menu[i].name+' </b></span><br>'+menu[i].ingred+'</td><td>'+menu[i].price+'</td></tr>');
$('#menutable tr').attr('data-id', menu[i].id);
id.push( $('#menutable tr').attr('data-id'));
}
console.log(id);
});


Now on click on any row, I want to retrieve the id of that certain product.

$(document).on('click','tr', function() {
var id = $(this).attr('data-id');
console.log(id);
});


But when I test it with console.log, I only get the last product id, no matter what row I click on. Any suggestions what I am doing wrong?

Answer

Data Attributes should be lower case. Change it to data-id.

Since you're looking for the value of a data attribute you can use jQuery's .data() to get the value, and use $(this) to get the jQuery item that was clicked:

var id = $(this).data('id');

EG:

var menu = [];
menu.push({id:"1",num:1,name:"one",ingred:"uno",price:"1.11"});
menu.push({id:"2",num:2,name:"two",ingred:"dos",price:"2.22"});

$(function(){//on document ready...
  
    (function addMenuToTable(){
        for (var i in menu){
            $('#menutable').append('<tr data-id="'+menu[i].id+'" class="product" role="button" data-ID=""><td class"num">'+menu[i].num+'</td><td class="td-width"><span><b>'+menu[i].name+' </b></span><br>'+menu[i].ingred+'</td><td>'+menu[i].price+'</td></tr>');
        }
    })();//IIFE
  
    //listen for clicks
    $('#menutable').on('click','tr', function(){
        var id = $(this).data('id');
        alert(id);
    });
  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="menutable"></table>

Comments