Stop form submission with submit eventlistener

前端 未结 3 837
清酒与你
清酒与你 2020-12-17 04:26

I\'m trying to stop a form from submitting using the submit eventlistener. My anonymous function runs but the form still submits, even with return false at the end of the fu

3条回答
  •  渐次进展
    2020-12-17 05:01

    Well this is the way I would do it :

    function validate (form)
    {
        // return false if some fields are not right
    }
    
    function setup_form_validation (form)
    {
        form.addEventListener (
            'submit',
            function (f) { // closure to pass the form to event handler
                return function (evt) {
                    if (!validate (f)) evt.preventDefault();
                    // Return status doesn't work consistently across browsers,
                    // and since the default submit event will not be called in case
                    // of validation failure, what we return does not matter anyway.
                    // Better return true or nothing in case you want to chain other
                    // handlers to the submit event (why you would want do that is
                    // another question)
                };
            } (form),
        false);
    }
    

    I would rather have a boolean holding the form validation status, though. Better update the status each time a field changes than do the check only when the user tries to submit the whole form.

    And of course this will fail in IE8- and other older browsers. You would need yet another bloody event abstraction layer to make it work everywhere.

提交回复
热议问题