JavaScript: add latest form event

78 views Asked by At

I'm writing a plugin and like to add a function to a submit/onsubmit event, that should only fire if all existing submit/onsubmit events return true. It is ensured that my javascript-file will be loaded at last, but I have no idea if there is already a listener on the submit event (e.g.from another plugin).

Let's assume I have this form:

<form action="" method="POST" onsubmit="return validateForm()" id="dummyform">
    Mandatory field:<br>
    <input type="text" name="required" id="required" value="">
    <br><br>
    <input type="submit" value="Submit" class="placeOrder">
</form> 

the on submit-Event validates the form and maybe there are some other events listening on the submit event. The validate form could look like this:

function validateForm() {
        var x = document.getElementById('required').value;
        if (x == "") {
            alert("required fields must be filled out");
            return false;
        }
        return true;
    }

Is there a way to ensure all existing listeners are executed and only if all return true, execute my function?

I tried something like this:

var classname = document.getElementsByClassName("hook");
Array.from(classname).forEach(function(element) {
    let form = findParentForm();
    bindEvent(form, 'submit', function(e){
       e.preventDefault();
       if(form.onsubmit() === false)
             return false;
       modal.style.display = "block";
       return false;
       });
});

BindEvent is just a function to support IE8. It does a element.addEventListener(eventName, eventHandler, false); or element.attachEvent('on' + eventName, eventHandler);

0

There are 0 answers