简体   繁体   中英

onclick delete will always delete the last row of the table

I have this inside a while loop. Everytime I confirm the onclick delete of any table row it always deletes the last row.

echo '<td><a href="#openModal'.$id.'" data-toggle="modalDialog" data-target="#openModal"><img src=img/view.png width=20px height=20px id="view"></a></td>';
echo '<td><a href="#" onclick="deleteShit()"><img src="img/delete.png" width=20px height=20px name="delete"></a></td></tr>';
?>
<script type="text/javascript">
function deleteShit()
{
    if (confirm('Delete?'))
        window.location='delete.php?id=<?php echo $id;?>'
}

this is the delete.php page

$id=$_GET['id'];

$query = "UPDATE `main` SET status=0 where id = $id";
$sql = $db->prepare($query);
if ($sql->execute()) {
    echo "<script>
            window.alert('Item deleted!')
            window.location='view.php';
        </script>";
}

You must write your javascript function outer the while, with an arg :

<script type="text/javascript">
function deleteShit(id)
{
    if (confirm('Delete '+id+'?')) {
        window.location = 'delete.php?id='+id;
    }
}
</script>

And call the function with the arg :

echo '<td><a href="#" onclick="deleteShit(\''.$id.'\')"><img src="img/delete.png" width=20px height=20px name="delete"></a></td></tr>';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM