Reputation: 1913
I render data from a Mysql database to a clientside browser using a php script with jquery
Datatables. When a user clicks an Update button inside the Edit column, I want to take the cell value of the row and fill a form so the user can update the information. The main problem is the jquery
on.('click', 'button', function)
does not want to get the table.row
data. The on click function is working though.
php script that renders the table:
<table id="usert" class="display" style="width:100%">
<thead>
<th>Id</th>
<th>User</th>
<th>Usernames</th>
<th>Email</th>
<th>Employee</th>
<th>Product</th>
<th>Admin</th>
<th>Active</th>
<th>Edit</th>
</thead>
<tbody>
<?php
//Select all users names from database and populate the select tag
include_once './db/dbconnect.php';
include_once './db/website/dbfunc_web.php';
$db = connectBlind();
$users_i = findUsers($db);
$cnt = 0;
if ($users_i != false) {
foreach ($users_i as $key => $value) {
$cnt ++;
echo "<tr>";
echo "<td>".$cnt."</td>";
echo "<td>".$key."</td>";
foreach ($value as $key => $val) {
if ($key === 'emp_priv' || $key === 'prod_priv' || $key === 'admin_priv' || $key === 'active') {
if ($val === 1) {
echo "<td>Yes</td>";
} else {
echo "<td>No</td>";
}
} else {
echo "<td>".$val."</td>";
}
}
echo "<td><button style="."'background-color: #3CB371; border: none; color: white; font-size: 14px; padding: 8px 10px; border-radius: 8px;'".">Update</button></td>";
echo "</tr>";
}
}
?>
jquery functions:
$(document).ready( function () {
$('#usert').DataTable();
});
$('#usert tbody').on( 'click', 'button', function () {
var data = table.row( $(this).parents('tr') ).data();
window.alert( data[1]);
} );
I want to get the single table.row
data of the specific Update button clicked?
Upvotes: 1
Views: 2227
Reputation: 10237
You can get the <tr>
using the closest()
and then the get()
to get each index.
$('button').on('click', function() {
let td = $(this).closest('tr').find('td');
let result = {
id: td.get(0).innerText,
user: td.get(1).innerText,
username: td.get(2).innerText
};
console.log(result)
});
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
<table>
<thead>
<th>Id</th>
<th>User</th>
<th>Usernames</th>
<th>Edit</th>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Jon</td>
<td>jon_bob</td>
<td><button>Edit</button></td>
</tr>
<tr>
<td>2</td>
<td>bob</td>
<td>bob_jon</td>
<td><button>Edit</button></td>
</tr>
</tbody>
</table>
Upvotes: 2