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??
CodePudding user response:
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
<?php
foreach ($customers as $customer)
{
echo '<button id="btn'. $customer['id'] . '" onclick="showDelete('.$customer['id'].')">'.$customer['name'].'</button>
<button id="btn-delete' . $customer['id'] . '" value="'.$customer['id'].'" style="display:none;">Delete</button>
';
}
<script>
function showDelete(id)
{
let deleteId = id
let btn = document.getElementById("btn-delete" id)
let deleteValue = btn.value
console.log(deleteValue)
if ( deleteId === deleteValue ){
document.getElementById("btn-delete" id).style.display = "block";
}
</script>
CodePudding user response:
In the PHP code, the $customer['id']
is appended to the id
string and also added as a value
property. In the JavaScript code, the comparison between deleteId
and deleteValue
is unnecessary because they have been set as the same value.
function showDelete(id) {
document.getElementById("btn-delete" id).style.display = "block";
}
CodePudding user response:
This might be helpful
- php:
<?php $customers = (object) [
['name' => 'foo', 'id' => 1],
['name' => 'bar', 'id' => 2],
['name' => 'baz', 'id' => 3],
]; ?>
<?php foreach ($customers as $customer) : ?>
<button id="_<?= $customer['id'] ?>" onclick="showDelete(_<?= $customer['id'] ?>)"><?= $customer['name'] ?></button>
<?php endforeach ?>
- JavaScript
<script>
function showDelete(el) {
el.parentNode.removeChild(el);
}
</script>