0

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.

cgrouge
  • 177
  • 2
  • 16
  • You need to pass the event into the handler, and `preventDefault()` otherwise it will do a form submission, which isn't async. – Sterling Archer Jun 21 '17 at 15:12
  • @SterlingArcher sorry if I don't follow, but I need to add preventDefault to the submit function? – cgrouge Jun 21 '17 at 15:35

2 Answers2

0

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.

  • I'm not sure I understand your answer. My button is outside of the form so the script is there to submit the form when I click that button. I want the form to submit but not redirect to the thank you page. Your answer doesn't provide that solution – cgrouge Jun 21 '17 at 15:44
  • Where the form is directed depends on your action value. The above form is being submitted. That is what document.getElementById("form").submit(); is doing. – PhilipAbbott Jun 21 '17 at 15:45
  • Right, the form submission in your answer is working but I don't want the page redirection. So, I want the data to submit in the action URL but I don't want the thank you page to appear when it's complete – cgrouge Jun 21 '17 at 15:51
-1

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