Pregunta

I know I know; there's a lot of posts on the internet about this. I know I need to use <form action="index.html" onSubmit="return checkTheForm()"> But I just don't understand why the code I wrote doesn't seem to work.

In my HTML I've got the following:

<form method="post" action="/index" onsubmit="return validateBuyForm();">
    <input id="agreeToTerms" name="agreeToTerms" type="checkbox" /> I agree<br />
    <input value="Buy that stuff!!" id="pay" type="submit" />
</form>

and in my js I've got this:

function validateBuyForm() {
    alert('we are validating!!');
    return false;
}

JSFiddle here: http://jsfiddle.net/zx2rx/

My problem is that I never see the alert, even though I think I'm following all the tutorials on the internet. Does anybody have the winning tip on what I'm doing wrong here?

All tips are welcome!

¿Fue útil?

Solución

That problem is just a JsFiddle problem. Functions declared in JsFiddle are automatically wrapped in their own scope, so they are not global and therefore not visible to the code declared in your onsubmit attribute. If you force the function to be global it will work:

window.validateBuyForm = function() {
    alert('we are validating!!');
    return false;
}

Update fiddle

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top