Search code examples
javascriptjqueryhtmlpreventdefaultonsubmit

Form still submits, trying to use e.preventDefault();


So I have this form. I want to check if user has validaty the captcha, but have problems. Here is the form, that checks the function.

<form data-id="embedded_signup:form" id="myForm" class="ctct-custom-form Form" name="embedded_signup" method="POST" action="https://visitor2.constantcontact.com/api/signup" onsubmit="check_if_capcha_is_filled()">

Here is the function that determines whether doSubmit (the captcha) has been validated.

function check_if_capcha_is_filled(e){
  if(doSubmit) return true;
  e.preventDefault();
  alert('Fill in the capcha!');
  return false;
};

But I get an error

Uncaught TypeError: Cannot read property 'preventDefault' of undefined
at check_if_capcha_is_filled

Any pointers to what I am missing? Thank you.


Solution

  • Your e.preventDefault is being used incorrectly. It will do nothing because you're passing an event to a function, you want to attach it to the event handler like this:

    $('form').on('submit', function(e)
    {
        e.preventDefault();
        //rest of code
    })
    

    this will stop the submit action.

    refs: http://api.jquery.com/event.preventDefault/