user3248186
user3248186

Reputation: 1558

How to get the data inside a html table cell when clicked on it?

I created a html table and filled it dynamically. So I want to alert the data inside a cell of the table when i clicked it. Here is the code for the table

JSP

<table id="load-opt"></table>

I'm filling the data inside dynamically like this

var fillTable = function($element, data) {
    var t_head = $("<tr></tr>");
    for(var ind=0; ind<data.length; ind++) {
        //name is the name and desc is the description for each option
        var $option = $("<tr></tr>");
        $option.html("<td>"+name+"</td><td>"+desc+"</td>");
    }
};

I tried this but it's not working, it's giving "undefined".

var choice = $('table#load-opt tr td');
choice.click(function(){
    alert(choice); // also tried alerting choice.textContent, choice.innerHTML and choice.firstChild
});

Upvotes: 1

Views: 142

Answers (2)

Musa
Musa

Reputation: 461

you are actually trying to alert the 'td' object not value of from that object so you can use following to solve the query.Here i am using on instead of direct click function because of dynamically added data.

var choice = $('table#load-opt tr td');
 choice.on('click', function(){
 alert($(this).text());
});

Upvotes: 1

Todd Mark
Todd Mark

Reputation: 1885

You can use $(this).text() to fetch the data in table cell. This is a link.

Upvotes: 0

Related Questions