2

I need to turn the default back on when my condition is true. Because I use the condition in an onclick of the submit button I can't put preventDefault inside it because it would prevent it after I clicked it and that would have no use.

So when the condition is true I need it to resume the form action. Also in the onclick I need it to react the first time and only once now +1 every time I click on it.

So in this case it has to alert Success at the first click and continue to the form page afterwards.

HTML:

<form id="formName">
    <input type="submit" id="submitBtn" value="Submit" />
</form>

JS:

var a = 1;  
$("#formName").submit(function(e){
    e.preventDefault();
        $(document).on("click", "#submitBtn", function () {
                if(a != 1){
                    alert("Fail!");
                }
                else{
                    alert("Success");
                    return true;
                }
        });
    });

Demo: http://jsfiddle.net/Z9Zwz/

  • Also, http://stackoverflow.com/questions/5651933/what-is-the-opposite-of-evt-preventdefault and http://stackoverflow.com/questions/1688567/is-there-an-opposite-function-of-preventdefault-in-javascript – dsgriffin May 27 '13 at 19:59
  • None of those answer my question. If I had it without the onclick I would just only use the preventDefault in the if statement with the false condition. But in this case that doesn't work for me. –  May 27 '13 at 20:04
  • @Xegano please also show the click handler function as well. I assume it is some form validation? – Andbdrew May 27 '13 at 20:07
  • I added a jsfiddle. Forgot to add it before –  May 27 '13 at 20:09

2 Answers2

0

Preventing default submit is harder than it should be imo. I've encountered several problems with it cross browser/platform.

I finally decided to remove the submit button and have the form submit with JQuery ajax, which you seem to be using. While hardcoding the form onsubmit to return false. That should make it much easier.

Jonathan
  • 8,771
  • 4
  • 41
  • 78
0

The problem is that the browser can only submit a form when a user clicks on a submit button. You cannot submit a form from JavaScript side sensu stricto. You can emulate this via AJAX though (which I strongly suggest).

If it was some other event I would suggest to wrap a button with a div, bind to click on div and then manually trigger the event later.

P.S. Don't add an event handler in event handler. You are stacking event handlers.

freakish
  • 54,167
  • 9
  • 132
  • 169