Skip to content
Advertisement

.click() on hidden input button doesn’t work (undefined)

I’ve spent hours and read countless stackoverflows but I can’t get this to work.

I’ve got a form (Caldera Form in WordPress) that has a submit button (in fact it’s an input tag). Via JS I added an event listener because I want to make a backup of the form data to my database. The event listener line:

document.querySelector(".submit-permanently").addEventListener("click", handleIorSaveClick);

The handleIorSaveClick function does the job pretty well and everything is fine so far. However it’s not submitting the form now any longer. Although I didn’t include a “prevent default” statement anywhere. It just calls my handleIorSaveClick function (which does the database magic) and nothing else. The form isn’t getting submitted any longer.

Because of this I had the idea to place a fake button that looks like the submit button while making the real submit button invisible. If the user clicks the fake button, the event listener is calling the handleIorSaveClick function and from within there I want to automatically click on the “real” submit button after the database magic is done.

To do this I included these three lines of code:

document.querySelectorAll('.real-submit')[0].style.visibility = "visible";
document.querySelectorAll('.real-submit')[0].style.display = "inline";
document.querySelectorAll('.real-submit')[0].click();

Oddly enough the first two lines are being executed: The button becomes visible. But the third line which (in my head) should simulate a user click on that button to actually submit the form won’t happen. I could even select the button in the chrome dev console with document.querySelectorAll(‘.real-submit’)[0] but this is giving me an undefined error: document.querySelectorAll(‘.real-submit’)[0].click();

Can anyone help me either telling me why the .click() doesn’t do anything or telling me why the event listener is preventing the form from being submitted in the first place?

Advertisement

Answer

You can do two things, In your first approach, without making fake submit button, at the end of handleIorSaveClick() function, unbind event listener from ‘.submit-permanently’ button and then call

document.querySelectorAll('.real-submit')[0].click();

Or in your second scenario, instead of

document.querySelectorAll('.real-submit')[0].click();

just do as this:

document.getElementById("myForm").submit();
Advertisement