2017-12-27 1214 views
-1

我试图创建一个调用“文件”类型输入事件的按钮,以便输入本身不显示,并且我可以按照this后的样式设置按钮的样式。形式看起来像这样:“.click();”触发器“onchange”

<form action="imageUpload.php" method="post" enctype="multipart/form-data" > 
    <input type="file" id="selectedImage" style="display: none;" onchange="this.form.submit()" /> 
    <button onclick="document.getElementById('selectedImage').click();" /> 
</form> 

当我点击该按钮,fileselect对话弹出,但文件被采摘前的“imageUpload.php”已经被调用。但是,当我通过删除按钮并显示输入本身来取出中间人时,它按预期工作:在选择文件后调用“imageUpload.php”。

我假设“.click();”函数触发“onchange”,即使值没有改变。它是否正确?有没有办法在不立即调用onchange的情况下从另一个按钮触发文件选择对话框?或者有没有办法来检查文件是否在onchange中被选中?

在此先感谢。

+1

使用按键的按键式按钮时,是在表单中。无类型按钮的默认操作是提交表单。还要注意,'button'不是自闭的,结束标签是强制性的。 – Teemu

+0

这里是https://jsfiddle.net/0423vd6f/ – RohitS

回答

1

提交<button>的默认类型。

在你链接的例子中,他们指定了这样的按钮:<button type="button">。通过给它一个这样的类型,表单不会被提交。

请参见:https://developer.mozilla.org/en-US/docs/Web/HTML/Element/button

+0

谢谢!这正是问题所在,我不知道默认的“按钮”会提交表单。看起来像一个奇怪的设计选择,但我想这简直就是HTML。 – Ikeaner

0

注:这只是为了说明的目的。您必须根据需要修改代码。当表单提交可能会显示错误,因为我们发布到一些随机的网址。

所以,让我们试着打破这个:

function showFile(){ 
 
    // lets trigger the file click as its hidden. 
 
    document.getElementById('fileControl').click(); 
 
} 
 

 

 
function sub(){ 
 
// check if your user has selected any file? 
 
if(document.getElementById('fileControl').files.length > 0){ 
 
// if you are curius to see your files log this 
 
//console.log(document.getElementById('fileControl').files); 
 
// do post your form here by 
 
    document.getElementById('testForm').submit(); 
 
} 
 
}
<!-- Change the action URL to what you want--> 
 
<form method="post" action="example.com" id="testForm"> 
 
<!-- Lets have hidden file control that calls the some method to submit form--> 
 
<input type="file" id="fileControl" onchange="sub();" style="display:none;"> 
 
<!-- Lets have a button to open file dialog--> 
 
<input type="button" id="btn" value="open" onclick="showFile();"> 
 
</form>