Below is the code of the page, however, you will see in the head that I have put in javascript that is supposed to check to see if there is a file selected via the file upload input field located at the bottom of the code. After it detects the file selection, then it is supposed to automatically submit the form, but for some reason it is not submitting automatically. Why isn't this working? Thanks in advance!
JavaScript: (in head
)
<head>
<script type="text/javascript">
document.getElementById("photofield").onchange = function() {
document.getElementById("form").submit();
}
</script>
</head>
HTML (Form):
<form enctype="multipart/form-data" action="photoupload.php" method="post" id="form">
<input type="hidden" name="MAX_FILE_SIZE" value="524288">
<p><input id="photofield" type="file" name="upload" /></p>
</fieldset>
<div align="center"><input type="submit" name="submit" value="Submit" /></div>
<input type="hidden" name="submitted" value="TRUE" />
</form>
It's because you have an input element ( submit button
) with name submit
and this is the problem, if you change the name of the submit button to something else than submit
then it'll work, for example, change your submit button code to btn_submit
instead of submit
<input type="submit" name="btn_submit" value="Submit" />
Now try this
window.onload = function(){
document.getElementById("photofield").onchange = function() {
document.getElementById("form").submit();
};
};
With the name submit
, it throws the following error
Uncaught TypeError: Property 'submit' of object #<HTMLFormElement> is not a function
it sets a property submit
to the HTMLFormElement
, so the method submit
in the prototype
of the form element can't be executed, check this working example (tested in Chrome only).
Also, it's important to register the event on window onload (also read addEventListener and read this too) event because the form is not available when your code runs in the head
section and it'll throw following error
Cannot set property 'onchange' of null
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.