Search code examples
javascriptformsprototypejs

stopping form submit with prototype.js


There seems to be a issue or my lack of knowledge how to stop the form to be submitted with prototypejs. Maybe someone can help me with the issue I'm facing

consider this simple form

<form id="formContact" method="post">
    <p>Name:
        <br />
        <input type="text" id="name" name="yourName" size="20" />
    </p>
    <p>E-mail:
        <br />
        <input type="e-mail" name="yourEmail" size="20" />
    </p>
    <p>Message:
        <br />
        <textarea cols="20" rows="10" name="yourMessage"></textarea>
    </p>
    <p>
        <input type="submit" value="Submit this form" name="submitButton" />
    </p>
</form>

and this little js snippet from protoype manual http://prototypejs.org/doc/latest/dom/Event/stop/

Event.observe('formContact', 'submit', function (event) {
    var login = $F('name').strip();
    if ('' == login) {
        Event.stop(event);
        // Display the issue one way or another
    }
});

$('formContact').submit();

all this in fiddle : http://jsfiddle.net/C3eFu/2/

now the issue here is it stops the form perfectly if button is clicked but not when form is submitted with javascript.? is this the 1% where prototype fails to stop the event?


Solution

  • According to a lot of Googleing apparently the onsubmit event is not fired on the form when the .submit() method is called. This is not a lack of PrototypeJS but more a behavior that has not been fixed in Javascript.

    You can make your code behave the way you want it to happen by calling the onsubmit handler and then watching if the event is stopped and then decide to fire the submit method()