I initially had some code written in PHP / HTML that when a button was clicked, the form action took the user to the PHP page called delete.php.
Now i want to add a function in javascript that asks the user whether they are sure they want to go through with the action once they click the button, but I'm not sure how to not let the PHP form submit the form action if the user chooses to cancel.
This is the code:
#delete buttons previous code: <form action='delete.php' method='post'>
echo "<form onsubmit='return setAction(this)' method='post'>";
echo "<td> <button onclick='askConfirm()' type='submit' name='deleteItem' value='" . $line['productCode'] . "' />Delete</button></td>";
echo "</form>";
# end table row and loop
echo "</tr>";
# javascript
echo '<script type="text/javascript">
function setAction(){
if (confirm("Are you sure you want to delete this?") == true) {
form.action = "delete.php";
}
else {
return false;
}
}
</script>';
My Answer:
The issue in your code is that the `setAction` function is not properly defined to take in the form as a parameter. You need to pass the form as a parameter to the function and then set the action based on the user's confirmation.
Here is the corrected code:
php
#delete buttons
echo "";
# end table row and loop
echo "";
# javascript
echo '';
In this code, the `setAction` function now takes the form as a parameter and sets the form action to "delete.php" only if the user confirms the deletion. If the user cancels, the function returns false, preventing the form from submitting.
Rate this post
3 of 5 based on 5439 votesComments