javascript - 为什么选择文件时此表单不自动提交?

标签 javascript php html file upload

下面是页面的代码,但是,您将在头部看到我已放入 JavaScript,该 JavaScript 应该检查是否通过位于底部的文件上传输入字段选择了文件代码。在检测到文件选择后,它应该自动提交表单,但由于某种原因它没有自动提交。为什么这不起作用?预先感谢!

JavaScript:(在 head 中)

<head>
    <script type="text/javascript">
        document.getElementById("photofield").onchange = function() {
            document.getElementById("form").submit();
        }
    </script>
</head>

HTML(表单):

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

最佳答案

这是因为您有一个名为 submit 的输入元素(submit 按钮),如果您将提交按钮的名称更改为其他名称,这就是问题所在submit 就可以了,例如,将提交按钮代码更改为 btn_submit 而不是 submit

<input type="submit" name="btn_submit" value="Submit" />

现在试试这个

window.onload = function(){
    document.getElementById("photofield").onchange = function() {
        document.getElementById("form").submit();
    };
};

使用名称submit,它会抛出以下错误

Uncaught TypeError: Property 'submit' of object #<HTMLFormElement> is not a function

它将属性submit设置为HTMLFormElement,因此表单的prototype中的方法submit元素无法执行,检查this working example (仅在 Chrome 中测试)。

此外,在窗口 onload 上注册事件也很重要(另请阅读 addEventListener 并阅读 this )事件,因为当您的代码在 head 部分运行时,表单不可用,并且会抛出以下错误

Cannot set property 'onchange' of null

关于javascript - 为什么选择文件时此表单不自动提交?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19739166/

相关文章:

php - 如何从 php 中的 db 确定今天日期以下的日期

PHP 将数组转换为对象

html - CSS 背景图片 : Bottom of Page

javascript - ExtJS 4 网格现在在取消隐藏 div 后显示

html - SEO 标题 vs alt vs 文本

javascript - 错误: $injector:modulerr AngularJS

javascript - 在 jquery 中排序事件

尝试隐藏表格行时出现 JavaScript 错误

javascript - CSJS 不更新 SSJS 设置的属性

javascript - 攻击者可以在关闭 JavaScript 的情况下绕过 Ajax Form