Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

pickab00's avatar

Jquery prevent default not working

So I have a form submission which I am preventing the default. So the code looks something like this.

$("#form").submit(function(e){

var allowSubmit = false;

if (!allowSubmit){
    e.preventDefault();
}

//run something here and say

var a = 1;

if (a != 1) {
    allowSubmit = false;
    console.log('failed');
}else{
    allowSubmit = true;
    console.log('works');
}

});

I don't see the problem with this code. The e.preventDefault(); works just fine. But console logs 'works' and it is supposed to set the allowSubmit variable to true correct? Then why is my form not being submitted now that the allowSubmit is true and preventDefault is no longer true?

0 likes
2 replies
Talinon's avatar
Talinon
Best Answer
Level 51

The problem is the scope within you have declared allowSubmit. Every time your function is called, it's being re-declared to false, which is preventing the default.

Move your decleration to the global scope:

var allowSubmit = false;

$("#form").submit(function(e){

if (!allowSubmit){
    e.preventDefault();
}

1 like
pickab00's avatar

@TALINON - This was the solution. Sorry I didn’t notice that before. Thanks a bunch. Although I used an alternative. I am calling:

$(‘#form’).unbind.(‘submit’).submit();

Please or to participate in this conversation.