JavaScript box is not working as expected
I have a problem with this script. When I click yes, it removes the user, which is ok. My problem is that it still deletes the user when I click Cancel. Any ideas?
<script>
function myFunction() {
var x;
if (confirm("Are You Want To Delete This User ?") == true) {
x = "delete.php";
} else {
x = "memberlist.php";
}
document.getElementById("demo").innerHTML = x;
}
</script>
+3
source to share
3 answers
- I am assuming your element is a link with "delete.php" as href - this is a VERY bad idea unless you want google spider to delete your database.
- You need to return false in the link click event if you don't want to execute it, but see 1
I suggest
window.onload=function() {
document.getElementById("deleteLink").onclick=function() {
if (confirm("Do you really want to delete?") {
location="delete.php?user="+this.getAttribute("data-user");
}
}
return false // cancel link
}
using
<a href="#" id="deleteLink" data-user="Frank">Delete</a>
Common for multiple users:
window.onload=function() {
var deleteLinks = document.querySelectorAll(".deleteLink");
for (var i=0;i<deleteLinks.length;i++) {
deleteLinks[i].onclick=function() {
var user = this.getAttribute("data-user");
if (confirm("Do you really want to delete "+user+"?") {
location="delete.php?user="+user;
}
}
}
return false // cancel link
}
using
<a href="#" class="deleteLink" data-user="Frank">Delete Frank</a>
<a href="#" class="deleteLink" data-user="Bob">Delete Bob</a>
0
source to share