Home > Net >  Using html and javascript to allow whether a form action gets called or not is not working (echoed i
Using html and javascript to allow whether a form action gets called or not is not working (echoed i

Time:12-15

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>';

CodePudding user response:

The solution is actually quite simple. This onsubmit attribute will prevent form submission if the confirmation dialogue is cancelled.

<form action="delete.php" onsubmit="return confirm('Do you really want to submit the form?');" method="post">
    <input type="submit" name="submit">
</form>

  • Related