I am creating a small project which implements CRUDs on a MySQL table using PHP and jQuery. The table is injected into the layout this way:
<?php
require '../connect.php';
$sql = "SELECT id, countryName, shortDesc FROM countries";
$result = mysqli_query($conn, $sql);
echo "<table>
<tr>
<th>Id</th>
<th>Country</th>
<th>Short description</th>
<th>Actions</th>
</tr>";
while ( $row = $result->fetch_assoc() ) {
echo "<tr>
<td>".$row["id"]."</td>
<td>".$row["countryName"]."</td>
<td>".$row["shortDesc"]."</td>
<td>
<button id='show' value=".$row["id"].">Show</button>
<button id='edit' value=".$row["id"].">Edit</button> // value field added to pass id data
<button id='delete' value=".$row["id"].">Delete</button>
</td>
</tr>";
}
echo "</table>";
$conn->close();
?>
I added value fields to the buttons because I was thinking of using this property to pass the row's ID to the JS script which should load the EDIT page.
I used the event delegation to access the button but just after that i have no idea about accessing the value property of the button.
On my jQuery scripts file I wrote this code to test:
// EDIT
$('#content').on('click', '#edit', function() { // EVENT DELEGATION
// THIS DOESN'T WORK
var id = $('#content').children('#edit').attr("value");
alert( id ); // RETURN UNDIFINED
});
I tried to access a property of the content element and it work, so the problem should be that I cannot access his children like that (in a similar way to the even delegation with .on()).
there will probably be a more elegant way than this to solve the problem but in the meantime I would like to understand how to access the properties of AJAX injected HTML elements!