最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to get td values from dynamically created table - Stack Overflow

programmeradmin6浏览0评论

I see a lot of similar questions but not one that directly targets my problem. The business logic of my problem is that I allow the user to open a jQuery Dialog where I create table loaded with a data from a database and when the user make a choise I load the selected data info fields from the main screen.

My current problem is with collecting the data from the <tr> which happens on button click. If it was a hard coded table I would just:

$(selector).on('click', function(){
  var $item = $(this).closest("tr").find('td');
})

and then do something with $item however the table is created dynamically (from Ajax request) everytime the Ajax request is made the table is destroyed and recreated so basically I can't or at least I don't know a way to use some sort of selector to which to bind the event so I can reproduce the above code.

Instead in the dynamic table I have this:

      <td><button onclick="getData();return false">Select</button>

The problems with this (at least how I see it) are two - first, the using of onclick inside HTML element. From what I know it's not a good practice and there are better alternatives and I would appreciate answer showing this. Also, even though I go with this code I'm yet unable to extract the text from each <td> in:

function getData() {
...
}

I tried several approaches including the one which was working with the static table and the binded event handler.

At the end here is a JS Fiddle example where I think I made it clear what I can and what I can not do, so you can refer to it.

I see a lot of similar questions but not one that directly targets my problem. The business logic of my problem is that I allow the user to open a jQuery Dialog where I create table loaded with a data from a database and when the user make a choise I load the selected data info fields from the main screen.

My current problem is with collecting the data from the <tr> which happens on button click. If it was a hard coded table I would just:

$(selector).on('click', function(){
  var $item = $(this).closest("tr").find('td');
})

and then do something with $item however the table is created dynamically (from Ajax request) everytime the Ajax request is made the table is destroyed and recreated so basically I can't or at least I don't know a way to use some sort of selector to which to bind the event so I can reproduce the above code.

Instead in the dynamic table I have this:

      <td><button onclick="getData();return false">Select</button>

The problems with this (at least how I see it) are two - first, the using of onclick inside HTML element. From what I know it's not a good practice and there are better alternatives and I would appreciate answer showing this. Also, even though I go with this code I'm yet unable to extract the text from each <td> in:

function getData() {
...
}

I tried several approaches including the one which was working with the static table and the binded event handler.

At the end here is a JS Fiddle example where I think I made it clear what I can and what I can not do, so you can refer to it.

Share Improve this question asked Nov 13, 2014 at 10:58 LeronLeron 9,89640 gold badges168 silver badges265 bronze badges 5
  • 1 If you select the parent element where the table is created and bind an event to it like this $('#temp-table').on('click', 'table button', function(){, I think that the event it triggered, but I'm not sure. Check this fiddle. – DontVoteMeDown Commented Nov 13, 2014 at 11:06
  • @DontVoteMeDown Seems legit to me. If you want see Cerlin Bosses answer. Pretty close to yours. I can't decide if one is better than the other or are the same.. – Leron Commented Nov 13, 2014 at 11:25
  • He's answer is pretty close to mine, the difference is that I prefer to attach the delegation to the parent element, instead of the document itself. I think that there is no use to bind the event in the entire document, but its a minimal performance concern. – DontVoteMeDown Commented Nov 13, 2014 at 12:16
  • @DontVoteMeDown in fact I tried to attach the delegation to the divI'm using to create the jQuery dialog where everything else is appended afterwards but for some reason it didn't work while if I use document it's ok... any idea why? – Leron Commented Nov 13, 2014 at 12:19
  • Nope. Not sure why, but it worked on the fiddle I posted. Anyway, if it works to you, its ok. As I said, its just a minimal concern. I don't think binding event to document would decrease your app performace at all. – DontVoteMeDown Commented Nov 13, 2014 at 12:46
Add a ment  | 

3 Answers 3

Reset to default 5

Check this fiddle

$(selector).on('click', function(){
  var $item = $(this).closest("tr").find('td');
})

Using the above code you are binding a direct event but the one which you want is delegated event

To use delegated event you should use like

$(document).on('click',selector, function(){
  var $item = $(this).closest("tr").find('td');
})

so your final code will look something like

$(document).on('click','.get-data' ,function(){
    var $item = $(this).closest("tr").find('td');
    $.each($item, function(key, value){
        alert($(value).text());
    })
});

document can be anything which is parent to the table which is going to be created.

Dont forget to add the selector while adding a new table element

I had the same problem and solved it that way. You can create your table with the database results like this:

for (var i = 0; i < results.length; i++) {
   // create table row and append it to the table using JQuery
   // next create a td element, append it to the created tr
   // and attach a listener to it
   $('<td/>').html(results[i].textProperty)
             .appendTo($(tr))
             .on('click', getData);
}

where getData() is your function.

You can pass arguments to your getData like this:

.on('click', {info: results[i].data}, getData);

Then you can access them in your function:

function getData(event) {
    console.log(event.data.info);
}

Hope this helps!

Edit: This way you are creating a listener for each td. An optimization could be to create a listener for the whole class of td elements and to pass data to it via HTML attributes or text value like in the approved answer.

or you can use this pass object in getdata method

$('#build-table').on('click', function(){
        $('#temp-table').append('<table><thead><tr><th>Select</th><th>Name</th>    </tr></thead>' +
        '<tbody><tr><td><button class onclick="getData(this);return false">Select</button></td><td>Name1</td></tr>' +  
       '<tbody><tr><td><button onclick="getData(this);return false">Select</button></td><td>Name2</td></tr>' +
                                '</tbody></table>')
    });

    function getData(ob) {

    var $item = $(ob).closest("tr").find('td');
        $.each($item, function(key, value){
            alert($(value).text());
        })
    }
发布评论

评论列表(0)

  1. 暂无评论