Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Submit form with Javascript doesn't work

I have a simple form for uploading a file. If I use an ordinary 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 an ordinary button and use Javascript to submit the form, nothing happens:

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

I verified that the onclick handler really is getting called, and looking up the form works correctly. For example, if I change it to onclick="alert(document.getElementById('mainform').action)", the alert comes up as expected and shows the target URL of the form. But for some reason, the call to submit() simply doesn't submit the form.

like image 820
peastman Avatar asked Sep 19 '13 19:09

peastman


Video Answer


2 Answers

The issue is your submit button. Its id is submit, which means that document.getElementById("mainform").submit represents the button with ID of submit, not the submit function.

You just need to change the ID for that button, and you're all good.

like image 89
Joe Enos Avatar answered Sep 21 '22 10:09

Joe Enos


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

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

By having that id, a reference to it is being assigned to the submit property of the <form>, which replaces the method.

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

<input type="submit" id="mainform_submit" value="Analyze File"/>
like image 45
Jonathan Lonowski Avatar answered Sep 19 '22 10:09

Jonathan Lonowski