Question

I'm loading data using jQuery (AJAX), which is then being loaded into a table (so this takes place after page load).

In each table row there is a 'select' link allowing users to select a row from the table. I then need to grab the information in this row and put it into a form further down the page.

$('#selection_table').on('click', '.select_link', function() {
    $('#booking_address').text = $(this).closest('.address').text();
    $('#booking_rate').text = $(this).closest('.rate').val();
});

As I understand it, the 'closest' function traverses up the DOM tree so since my link is in the last cell of each row, it should get the elements 'address' and 'rate from the previous row (the classes are assigned to the correct cells).

I've tried debugging myself using quick and dirty 'alert($(this).closest(etc...' in many variations, but nothing seems to work.

Do I need to do something differently to target data that was loaded after the original page load? where am I going wrong?

Was it helpful?

Solution

You are making wrong assumptions about .closest() and how .text() works. Please make a habit of studying the documentation when in doubt, it gives clear descriptions and examples on how to use jQuery's features.

  • .closest() will traverse the parents of the given element, trying to match the selector you have provided it. If your .select_link is not "inside" .address, your code will not work.

  • Also, .text() is a method, not a property (in the semantical way, because methods are in fact properties in Javascript). x.text = 1; simply overrides the method on this element, which is not a good idea, you want to invoke the method: x.text(1);.

Something along these lines might work:

var t = $(this).closest('tr').find('.address').text();
$('#booking_address').text(t);

If #booking_address is a form element, use .val() on it instead.

If it does not work, please provide the HTML structure you are using (edit your question, use jsFiddle or a similar service) and I will help you. When asking questions like this, it is a good habit anyways to provide the relevant HTML structure.

OTHER TIPS

You can try using parent() and find() functions and locate the data directly, the amount of parent() and find() methods depends on your HTML.

Ex. to get previous row data that would be

$('#selection_table').on('click', '.select_link', function(){ 
     $('#booking_address').text = $(this).parent().parent().prev().find('.address').text();
});

Where parent stands for parent element (tr), then prev() as previous row and find finds the element.

Is there a demo of the code somewhere? Check when are you calling the code. It should be after the 'success' of AJAX call.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top