开发者

submitting when onchange event is triggered on an input element with type "file"

开发者 https://www.devze.com 2023-03-17 01:38 出处:网络
I am tryi开发者_开发技巧ng 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.

I am tryi开发者_开发技巧ng 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.

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.

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 :))

0

精彩评论

暂无评论...
验证码 换一张
取 消