Search code examples
javascriptformsconfirm

Confirm before executing secondary option in form


I have a form where a user can choose to modify or delete records from a db, based on which button they select in the form. It works great if I leave it just as an either/or, but I wanted to add a confirmation/warning before people deleting the files in case they accidentally clicked the wrong button. However, when I add the confirm feature, the form no longer executes the action if they click "OK" on the warning (it tries to execute the action called by clicking on the first button). Nothing happens if they hit cancel after the warning pops up (which is as it should be). But if I remove the confirm feature, both buttons work correctly (it just makes it more likely someone will accidentally hit the wrong button). I have found lots of questions on here on how to execute to actions with one click, but obviously I DON'T want it to execute immediately, so those aren't helpful.

Here is the code for the button I am trying to make work:

 <input type="submit" value="DELETE Selected Rows" onClick="return confirm('WARNING!! You are about to DELETE the selected rows; this action cannot be undone!'); submitForm('delete_record.php');">

However, if I just have:

<input type="submit" value="DELETE Selected Rows" onClick="submitForm('delete_record.php')">

it works fine.


Solution

  • Try this

    <input type="submit" id="submit-button" value="DELETE Selected Rows" onClick="if (confirm('WARNING!! You are about to DELETE the selected rows; this action cannot be undone!')) { submitForm('delete_record.php'); };">
    

    However I would recommend to use event binding instead using onclick-attribute. Example (Updated based on new information given by @sparrowhawk87 in the comments):

    <script>
    document.getElementById("my-form").addEventListener("submit", function(event){
            event.preventDefault();
    
        if (confirm('WARNING!! You are about to DELETE the selected rows; this action cannot be undone!')) { 
             alert("Execute submitForm() here.");
        };
    });
    </script>
    

    (Please note that you need to add an ID called 'my-form' to your form tag to make this example work.)