How to preventDefault inside method Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of How to preventDefault inside method without wasting too much if your time.

The question is published on by Tutorial Guruji team.

When executing submit, “e” is undefined… How to preventDefault and then execute()? I’ve tried “this.execute” (without brackets), but then the variable “form” is not accessible. Also tried this:

this.form.addEventListener("submit", function(e){e.preventDefault(); this.execute();}, false);

but not working.

class Filters {
    form;

    constructor(form) {
        this.form = form;
        this.form.addEventListener("submit", this.execute(), false);
    }

    execute(e) {
        e.preventDefault();
        [...]
    }
}

let f = new Filters([...],[...]);

Answer

You need to pass the event to your execute method as a parameter like shown below.

class Filters {
    form;

    constructor(form) {
        this.form = form;
        // Either use an arrow function or this.execute.bind(this) 
        this.form.addEventListener("submit", e => this.execute(e), false);
    }

    execute(e) {
        e.preventDefault();
        [...]
    }
}

We are here to answer your question about How to preventDefault inside method - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji