Sunday, June 2, 2024
 Popular · Latest · Hot · Upcoming
83
rated 0 times [  90] [ 7]  / answers: 1 / hits: 7190  / 10 Years ago, thu, november 13, 2014, 12:00:00

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.


More From » jquery

 Answers
7

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


[#41280] Wednesday, November 12, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
pranavrorys

Total Points: 466
Total Questions: 87
Total Answers: 115

Location: Barbados
Member since Sun, Nov 27, 2022
2 Years ago
pranavrorys questions
Fri, May 27, 22, 00:00, 2 Years ago
Thu, Oct 28, 21, 00:00, 3 Years ago
Sat, May 30, 20, 00:00, 4 Years ago
Fri, Dec 20, 19, 00:00, 5 Years ago
;