最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - Submit form with Javascript doesn't work - Stack Overflow

programmeradmin7浏览0评论

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 es 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.

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 es 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.

Share Improve this question edited Sep 19, 2013 at 19:08 Diodeus - James MacFarlane 114k33 gold badges163 silver badges180 bronze badges asked Sep 19, 2013 at 19:06 peastmanpeastman 1,2791 gold badge14 silver badges18 bronze badges 1
  • @kol: w3schools is not a good source for JavaScript code. Plus, how does his code differ from that? He's pretty much doing the same thing, – gen_Eric Commented Sep 19, 2013 at 19:14
Add a ment  | 

2 Answers 2

Reset to default 10

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.

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"/>
发布评论

评论列表(0)

  1. 暂无评论