简体   繁体   English

在“文件”类型的输入元素上触发 onchange 事件时提交

[英]submitting when onchange event is triggered on an input element with type “file”

I am trying to submit a form using the onchange event of an input element with type file but the problem is that an empty form is submitted instead even though a file is chosen.我正在尝试使用类型为 file 的输入元素的 onchange 事件提交表单,但问题是即使选择了文件,也会提交一个空表单。

here is the code:这是代码:

var form = document.createElement("form");
form.action="http://localhost:8084/upload/image";
form.method="post";
form.enctype ="multipart/form-data";
form.target="upload_target";

var input=document.createElement("input");
input.type="file";
input.accept="image/jpeg, image/gif, image/png";
input.onchange=function(ev){this.form.submit()};
form.appendChild(input);

The form submits correctly when a submit button is clicked but not when the state of the "file input" is changed.单击提交按钮时表单正确提交,但在“文件输入”的 state 更改时不正确。

Is there a way to achieve what I am trying to do?有没有办法实现我想要做的事情?

Are you getting an error?你有错误吗?

You have a syntax error.您有语法错误。 This line:这一行:

input.onchange=function(ev){this.form.submit());

Should be应该

input.onchange=function(ev){this.form.submit()};

Also, what browser are you using, because that technique to hook the event won't work in all of them (like non-modern IE:))另外,您使用的是什么浏览器,因为挂钩事件的技术不适用于所有浏览器(如非现代 IE :))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM