Question

<form method="post" action="/Order/CheckOut/" onSubmit="return Validate()">

and then...

function Validate() {
    alert($("#email").val());
    return false;
}

The messed up part is when I take out the alert it works fine, the submit fails, but when I put the alert in, it allows the submit to go through... what the heck?

I also tried this:

function Validate() {
    if(document.getElementByID("email").value == "test"){
        alert("It says test.");
    }
    return false;
}

and got the same behavior, it would never make it to the return statement...

If I step through the JS with firebug and break at the alert or the if (depending on the version above) it stops there, and I click 'step into' and it just submits the form, why isn't it making it to the return false line?

Was it helpful?

Solution

Why not wrap it in a try block?

function Validate() {
    try {
        alert($("#email").val());
    } catch (e) {
        alert("Problem: " + e);
    }

    return false;
}

OTHER TIPS

You could use event.preventDefault() instead.

$("form[name='myForm']").submit(function(e){
  e.preventDefault();
  alert($("#email").val());
});

You should attempt to keep your javascript, css, and html all seperate. Don't integrate them, or you'll make the project more difficult to manage. Instead of using the onsubmit attribute in HTML, simply append your logic to the $.submit() method of the form from your javascript as I did above.

This example assumes that you've given your form a name of "myForm." I merely used this in the example as you should itendify which form you're handling the submit-event of, and not use a generic $("form") selector.

If you're already using jQuery you're doing the whole thing wrong to begin with. You shouldn't be manually specifying the onSubmit handler from within the <form> element. Do as @Jon suggested and just bind the submit event:

$("form").submit(function() {
    alert($("#email").val());
    return false;
});

The problem isn't that your function is returning true. The problem is that the JavaScript in the alert is failing and JavaScript quits interpreting the code. At which point, the browser is continuing with the default action which is to submit the form.

This is why Jonathan Sampson suggests using e.preventDefault() before the alert(), this way the browser doesn't continue with its default behaviour when the alert() fails.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top