简体   繁体   中英

jQuery form doesn't submit after correcting failing validation

I have a simple form, that asks if you're sure you want to submit it.

$(document).ready(function(){
  $("form#myform").on('submit', function(e)
  {
      if (!confirm('Are you sure?')){
        e.preventDefault();
      }
      else {
        console.log("submitting...");
      }
   });
});

Submit form, hit "ok" to the "are you sure" prompt, form submits just fine.

--refresh the page, clean slate--

Submit form, hit cancel to the "are you sure" prompt. Form does not submit, as expected. Submit form again, hit "ok" to the "are you sure" prompt, form still does not submit, "submitting..." gets logged to console. From this point on, the form will never submit until I refresh the page and hit "ok" to the prompt the first time.

If I swap

e.preventDefault();

with

return false;

nothing changes, exact same behavior.

I'm completely stumped. What am I doing wrong?

edit: Here's a jsFiddle link https://jsfiddle.net/8ac3Lgzg/ . The HTML and JavaScript in that fiddle are /exactly the same/ as the code I have in my project. The issue I describe above does NOT happen when run on jsFiddle, but does in my project.

Your code works perfectly, here is a jsFiddle demonstrating it. I literally copy and pasted, there must be some other javascript influencing the form somewhere on your page.

jsFiddle link below

http://jsfiddle.net/xbhvqvp7/1/

Also might be worth checking the in browser network logs to see if the form is actually being submitted

The issue occurs due to a piece of code another developer on my team wrote that I was unaware of, that attaches to every form and caches it's onSubmit handler result. Because my form would return false upon failing validation, that result would be cached for the next attempted submission even if it passed validation.

Without wanting to break his code, my solution was to add an attribute to my form, "no-cache", and I updated his method to check for that attribute. This has solved my problem.

Thanks to everybody who helped, I greatly appreciate it!

try this manner

function SendForm(){
    if (!confirm('Are you sure?')){
        return false;
    }
    else {
        console.log("submitting...");
        return true;
    }
}

put the function sendForm in the submit button like this

<input type="submit" value="submit" onclick="return SendForm();" />

obviously not display anything on the console because when you submit the form, the browser reloads

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM