submitting form and using preventDefault() in validation but can no longer submit form after validation is addressed php/jquery

16 hours ago 1
ARTICLE AD BOX

I am trying to submit a form and validating data using jquery by calling preventDefault() when its incorrect. After addressing the validation error, what I want is to submit the form when the submit button is pressed again, but for some reason it no longer submits. Here is my code:

html:

<form id="myForm" method="POST"> <input type="text" id="inputA" name="inputA" value="1"> <input type="text" id="inputB" name="inputB" value="2"> <input type="submit" name="go" id="go" value="Submit this" class="btn"> <input type="text" name="message"> </form>

jquery:

$(document).on('click', '#go', function(){ var inputA= $('#inputA').val(); var inputB= $('#inputB').val(); if(inputA != inputB){ alert("not same!"); $(document).on('submit', '#myForm', function(e){ e.preventDefault(); }); }else{ $(document).on('submit', '#myForm', function(e){ if( $(this).hasClass('form-submitted') ){ e.preventDefault(); return; } $(this).addClass('form-submitted'); }); $("[name='message']").html("Please wait, i am being submitted."); } });

php on submit:

if(isset($_POST['go'])){ //do stuff here echo '<script>alert("Submission successful!")</script>'; echo '<script>window.close()</script>'; }

As you can see, i use preventDefault() when the values are not correct. I can change it then press the submit button again, but it only shows the message "Please wait, i am being submitted." and does not reload to go to the success script. Is there something wrong with my code? I might resort to ajax to this one, but I'm really just wondering why this does not work? I tried searching for similar situations but didnt find any explanation.

P.S. the addClass 'form-submitted' is a precaution for not double submitting i found here in stackoverflow.

Read Entire Article