I have a table that is being populated by a foreach loop to get data from a database:
foreach ($retrieve_data as $retrieved_data) {
$content .= "
<tr id=\"id_$retrieved_data->id\">
<td> $retrieved_data->id </td>
<td> $retrieved_data->posname </td>
<td> $retrieved_data->month </td>
<td> $retrieved_data->year </td>
<td> $retrieved_data->availableinv </td>
<td> $retrieved_data->maxinv </td>
<td> <button type=\"button\" id=\"editImpressionsBtn\" value=\"Edit\">Edit </button>
</tr>";
}
I want to write a jQuery function that gets data from the table like the id, availableinv, and maxinv when the edit button is clicked.
jQuery(document).on('click', 'editImpressionsBtn', function() {}
How can I assign a variable in this function to the data in each of these columns for only the row that the edit button was clicked?
Something like this? One thing I noticed, you need to make sure to add the selector (. or # for class or ID) to the handler.
$('.table_selector tbody').on('click', '.editImpressionsBtn', function(){
row = $(this).closest('tr');
})
Then you can add values or ids and get them like this
var my_id_value = row.attr('id')
Target the TR and then the different TD's
$('#editImpressionsBtn').on('click', function() {
var tr = $(this).closest('tr');
var tds = tr.find('td');
var id = tds.eq(0).text();
var avb = tds.eq(4).text();
});
If you're generating more than one table on the serverside, make sure you don't use the same ID for all of them, use a class instead.
There are three parts to this answer. Two are core to your question, one is a coding option / improvement:
First:
As your table is being built in a loop, I presume you've got multiple rows. Be aware that you can not have multiple buttons with the same ID. This is not only semantically incorrect, it will cause issues with jQuery. So, change the id of the button to be a class instead:
<button type="button" class="editImpressionsBtn" value="Edit">Edit </button>
Second:
Now, in your jQuery, you can access that row fairly easily:
jQuery(document).on('click', 'button.editImpressionsBtn', function() {
var row = $(this).closest('tr');
var id = row.find('td:eq(0)').text();
var posname = row.find('td:eq(1)').text();
// ... etc
});
Third:
Escaping quotes inside of quotes like you are doing is a pain to code, and more difficult to maintain and read. I'd recommend in this case using a HEREDOC.
Example:
$content .= <<<HTML
<tr id="id_$retrieved_data->id">
<td> $retrieved_data->id </td>
<td> $retrieved_data->posname </td>
<td> $retrieved_data->month </td>
<td> $retrieved_data->year </td>
<td> $retrieved_data->availableinv </td>
<td> $retrieved_data->maxinv </td>
<td> <button type="button" class="editImpressionsBtn" value="Edit">Edit </button>
</tr>
HTML;