javascriptformsvalidationsubmitonsubmit

Trigger onsubmit without submit-button


I'm stuck, trying to submit my form using the submit function (formElement.submit()).

Well, actually It do send the form-input-values to the backend, but I'm trying to prevent it and adding ajax in between.

Jade/pug

form#score-form(method="POST" action="/leaderboard")
    input#submit-score(type="hidden" value="" name="submitscore")
    //value is fetched from JS

JS

scoreForm.submit();
scoreForm.addEventListener('submit', function(){
    //Nothing here will be invoked
});

However, when using a submit button, it works as intended

form#score-form(method="POST" action="/leaderboard")
    input#submit-score(type="hidden" value="" name="submitscore")
    button(type="submit")

scoreForm.submit();
scoreForm.addEventListener('submit', function(){
    console.log("works"); //logs works
});

Everything works fine except the fact that it seems that .submit() doesn't invoke onsubmit. Is there any workaround (preferably with vanilla js), to give the program a hint that the form is submitted, even with .submit()?

Thanks


Solution

  • You need to add the listener before you actually submit:

    scoreForm.addEventListener('submit', function(){
        console.log("works"); //logs works
    });
    scoreForm.submit();
    

    Otherwise the event will have fired before you have a listener set up

    Edit: it seems I misread what you were asking. The answer you're looking for is that submit() will not fire the listener. you can simulate it by programatically clicking on the button with click(). Here is a good explanation of this behaviour. try:

    scoreForm.querySelector('input[type="submit"]').click()