So i have a list of customers with name and id in a button and i will like to delete each customers by obviously targeting the id.
<?php
foreach ($customers as $customer)
{
echo '<button id="btn" onclick="showDelete('.$customer['id'].')">'.$customer['name'].'</button>
<button id="btn-delete" value="'.$customer['id'].'" style="display:none;">Delete</button>
';
}
<script>
function showDelete(id)
{
let deleteId = id
let btn = document.getElementById("btn-delete")
let deleteValue = btn.value
console.log(deleteValue)
if ( deleteId === deleteValue ){
document.getElementById("btn-delete").style.display = "block";
}
</script>
Any time i trigger the button only the first value
of the delete
button shows
How do i target each name and delete them using vanilla javascript??
3
Answers
Simply slightly amend your code to include the id if you really wish to use the id approach
Assumption : the id (in this case is $customer[‘id’]) is
unique
(which is normally the case say if the id is the key), and if this is not the case, then create a unique id by say incrementing a variable such as $index inside the loop.So the code is
In the PHP code, the
$customer['id']
is appended to theid
string and also added as avalue
property. In the JavaScript code, the comparison betweendeleteId
anddeleteValue
is unnecessary because they have been set as the same value.This might be helpful