1

I have a form which is submitted using Ajax.

If a checkbox is checked (receive latest offers and such), I would like to prevent the form from being submitted, if the fields are not filled out.

If the checkbox is not checked, then I don't care if the fields are filled out, and the form can be submitted even if empty.

The problem I'm currently having is, that the form is being submitted even if the checkbox is checked and the fields are empty.

I tried return false, event.stopImmediatePropagation(), event.stopPropagation() and event.preventDefault();. None of them prevent the form from submitting.

function check() is attached to the submit button.

Any and all advice is welcome.

If I can provide any additional information, let me know.

Thank you

function check (event) {
    if (adverts.checked === true){
    // if the email field is valid, we let the form submit
        if (!fname.validity.valid) {    
        // If it isn't, we display an appropriate error message
            showNameError();
            return false; //event.preventDefault()//etc etc
        }
        if (!email.validity.valid) {
            showEmailError();
            return false; //event.preventDefault()//etc etc
        }
    };
};
setTimeout(function() {
document.getElementById("allow").addEventListener("click", sendAjax);
}, 1);
<button id="allow" onclick="check()">
    <span id="a"></span>
</button>
DoomBot
  • 82
  • 8

2 Answers2

0

I guess the problem is that you stop button.onclick from propagation, not form.onsubmit. Try moving check() from onclick to onsubmit:

<form id="fname" ... onsubmit="check(event)">
  <button id="allow" type="submit"></button>
</form>

Function check() should work without any edits then.

Also, see code from this question

General Grievance
  • 4,555
  • 31
  • 31
  • 45
RollingHog
  • 121
  • 7
0

As chandan suggested, I edited function check() and it works.

RollingHogs answer should also work, but the button I'm using is not type submit, as a few other ajax functions need to run before the form is submitted, so I can not accept that.

Anyway, this is the code that does the job:

function check (event) {
    if (adverts.checked === true){
    // if the email field is valid, we let the form submit
        if(!fname.validity.valid && !email.validity.valid){
            showNameError();
            showEmailError();
        }else if (!fname.validity.valid) {
        // If it isn't, we display an appropriate error message
            showNameError();
        }else if(!email.validity.valid) {
            showEmailError();
        }else{
            sendAjax();
        }
    }else{
        sendAjax();
    };
};
DoomBot
  • 82
  • 8