Search code examples
javascripthtmldom-eventsprompt

event.preventDefault() works for me on Chrome but not Firefox, why?


In Chrome, if the cancel button in window.confirm is clicked then the close day action (powered by a go backend) is not triggered. However, in Firefox the event is triggered even if cancel is clicked. Both browsers support event.preventDefault so I don't understand why it works in Chrome but not the Firefox.

My Javascript:

document.getElementById("closeDay").addEventListener("click", createAlert);
    function createAlert(){
            x = window.confirm("Are you sure?");
            if(x === false){
                    event.preventDefault()
            }
    }
    

My Html:

<form method="POST" action="/closeDay" id="closeDay">
    <input type="submit" value="Close Day" />
</form>

I've tried moving the id from form to input but that makes no difference. I also moved my js script to the bottom of the file just in case, though that also hasn't solved the issue.


Solution

  • You need to pass event as a function parameeter

    function createAlert(event){
      x = window.confirm("Are you sure?");
      if(x === false){
      event.preventDefault()
      }
    }