Khkhy Khkhy - 2 years ago 129
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'));

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');

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 Source

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');


var menu = [];

$(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>');
    //listen for clicks
    $('#menutable').on('click','tr', function(){
        var id = $(this).data('id');
<script src=""></script>
<table id="menutable"></table>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download