Submit form with javascript not working

I have a simple form to upload a file. If I use the regular submit button, everything works as expected:

<form id="mainform" method="post" action="/" enctype="multipart/form-data"> ... <input type="submit" id="submit" value="Analyze File"/> </form> 

But if I change it to a regular button and use Javascript to submit the form, nothing happens:

 <input type="button" id="submit" value="Analyze File" onclick="document.getElementById('mainform').submit()"/> 

I checked that the onclick handler is indeed called and the form search is working correctly. For example, if I changed it to onclick="alert(document.getElementById('mainform').action)" , the warning will appear as expected and display the destination URL of the form. But for some reason, calling submit () just doesn't submit the form.

+4
source share
2 answers

The problem is your submit button. Its submit identifier, which means document.getElementById("mainform").submit represents a button with a submit identifier, not a submit function.

You just need to change the identifier for this button, and all is well.

+8
source

You have a name conflict between the .submit() method and:

 <input type="submit" id="submit" value="Analyze File"/> 

Having this id , a reference to it is assigned to the property submit <form> , which replaces the method.

If you rename <input> , you should be able to .submit() as expected:

 <input type="submit" id="mainform_submit" value="Analyze File"/> 
+4
source

All Articles