Onsubmit event refusing to fire

Viewed 49

So I have this code.

class Validationator
{
    constructor()
    { 
        this.initValidation()
    }

    initValidation()
    {
        window.addEventListener("load", this.PerformOnLoad, false);
    }

    PerformOnLoad()
    {
        var form = document.querySelector("#feedbackcontainer");

        form.addEventListener("onsubmit", this.SubmitClicked);
    }

    SubmitClicked()
    {
        alert("asdf");
    }
}

I have tried using both 'submit' and 'onsubmit' and neither are working. I have verified that the query selector is grabbing the proper form. Pardon my being a beginner at Javascript. Event handlers keep defeating me.

3 Answers

The name of the event doesn't include the on prefix -- that's only used in the corresponding attribute name.

Also, if you use a class method as a callback function, you need to bind it to the object. Otherwise, this in the method will be the global window object, not the Validationator object.

class Validationator
{
    constructor()
    { 
        this.initValidation()
    }

    initValidation()
    {
        window.addEventListener("load", this.PerformOnLoad.bind(this), false);
    }

    PerformOnLoad()
    {
        var form = document.querySelector("#feedbackcontainer");

        form.addEventListener("submit", this.SubmitClicked.bind(this));
    }

    SubmitClicked()
    {
        alert("asdf");
    }
}

form.addEventListener("onsubmit", this.SubmitClicked); onsubmit is wrong the correct is form.addEventListener("submit", this.SubmitClicked); and any other codes?

At the PerformOnLoad() function there can not be onsubmit event, it would be just submit.

As well as, you need to use bind while you call the PerformOnLoad() and SubmitClicked() methods. In that case, the final code would be like,

class Validationator
{
    constructor()
    { 
        this.initValidation()
    }

    initValidation()
    {
        window.addEventListener("load", this.PerformOnLoad.bind(this), false);
    }

    PerformOnLoad()
    {
        var form = document.querySelector("#feedbackcontainer");

        form.addEventListener("submit", this.SubmitClicked.bind(this));
    }

    SubmitClicked()
    {
        alert("asdf");
    }
}
Related