Confirm on href link before deleting

I plan to have a confirmation box before the script deletes from the database, just in case of the wrong line been selected.

Code for the href

echo '<td align="center" valign="middle"><a href="delete.php?id='.$row["id"].'" class="confirmation"><img src="img/icon/delete.png"></a></td>';

Java script

<script type="text/javascript">
    var elems = document.getElementsByClassName('confirmation');
    var confirmIt = function (e) {
        if (!confirm('Are you sure?')) e.preventDefault();
    };
    for (var i = 0, l = elems.length; i < l; i++) {
        elems[i].addEventListener('click', confirmIt, false);
    }
</script>

When the 'delete' image is pressed it just deletes the row, no confirmation box appears?

Upvotes: 3

Views: 1625

Answers (3)

MahdiY
MahdiY

Reputation: 1306

try following code. You can do it without external javascript. just add confirm function in onlick event of your link.

PHP

echo '<td align="center" valign="middle"><a href="delete.php?id='.$row["id"].'" class="confirmation" onclick="return confirm(\'Are you sure?\');"><img src="img/icon/delete.png"></a></td>';

Upvotes: 0

Abozanona
Abozanona

Reputation: 2295

Make sure that the script tag is at the end of your page, or at least after the links.

Upvotes: 1

PHP

echo '<td align="center" valign="middle"><a data-href="delete.php?id='.$row["id"].'" href="javascript:;" onclick="confirmToDelete(this);"><img src="img/icon/delete.png"></a></td>';

JavaScript

<script>
  function confirmToDelete(element){
    if(!element) return false;
    if(confirm('Are you sure?')) self.location.href=element.getAttribute('data-href');
  }
</script>

Upvotes: 0

Related Questions