简体   繁体   中英

.submit and return false are not working on my form

I'm having trouble adding an event on a button that submits the form and after submission stopping the page redirect. I found other answers where I tried adding return false and preventDefault but neither are working.

Why is this not working?

function submitform() {
        document.getElementById("form").submit( function () {
            return false;
        });
    }

I added the click event to the button

<button id="button" onclick="submitform();">Submit Form</button

Here is an example that shows the javascript not working.

You are calling the function that is then listening for the form being submitted when there are no further events. Basically you are listening for an event that never comes.

There is no need to call the function on the submit in your supplied fiddle as the event is happening on the button.

I added a quick empty test for the email address just to show the process.

Amended Pen: https://codepen.io/anon/pen/dRRbyw

HTML

<button id="button" onclick="submitform();">Submit Form</button>
<br /><br />
<form id="form" method="post" action="https://submit.jotform.us/submit/71714528616156/">
  Email
  <input type="text" name="EMAIL" id="EMAIL" label="Email" value="">

JS

function submitform() {
    if(document.getElementById("EMAIL").value == "")    {    
          alert('nope');
          return false;
       } else {
    alert('yep');
    document.getElementById("form").submit();
  }
}

Let me know if you need any more explanation.

you can use ajax to handle the form submission without redirecting the page. You will need to be using jquery for this solution:

$(function() {
    $('form').submit(function() {
        $.ajax({
            type: 'POST',
            url: 'submit.php',
            data: { EMAIL: $(this).name.value }
        });
        return false;
    }); 
})

incredibly similar question/answer here: Prevent redirect after form is submitted

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