使用自定义按钮覆盖文件输入按钮

时间:2014-12-23 04:31:57

标签: jquery

我正在尝试输入type type = file。

当我尝试使用我的自定义按钮覆盖deault按钮时(以便我可以设置它)。我面临的问题是,当我点击我的自定义按钮时,表单会被提交并验证开始。有没有办法可以修复它。

HTML

<input type="file" name="upload" id="upload" class="upload"/>
<button class="fileButton" id="fileButton">Choose File</button>
<input type="submit" name="button" value="Contact Me" class="supportButton"></input>

上次输入是我的表单提交按钮。

使用Javascript:

<script type="text/javascript">
 $('#fileButton').click(function(){
 $('#upload').click();
 alert("input");
 });
</script>

当我点击我的自定义按钮时,它会触发文件上传按钮(我可以浏览并上传文件),但同时它会提交表单。

小提琴:http://jsfiddle.net/uw5wqxpw/

5 个答案:

答案 0 :(得分:2)

您需要禁止点击按钮的默认操作:

$('#fileButton').click(function(e){
    e.preventDefault();
    $('#upload').click();
    alert("input");
});

答案 1 :(得分:2)

如果您使用type="button",则无法提交表单。如果未声明,则type的默认buttonsubmit。因此,当您单击它时,它会按照默认行为提交表单

<button type="button" class="fileButton" id="fileButton">Choose File</button>

答案 2 :(得分:1)

当你的函数运行$('#upload').click()行时,它实际上模拟了被点击的按钮,因为它是.trigger("click")的简写,然后触发了提交按钮的默认行为。 我认为您需要的功能是$('#upload').on("click", clickHandler)

答案 3 :(得分:1)

jquery 文件添加到您的代码中。然后在jquery中使用trigger函数 它会起作用

&#13;
&#13;
 $('#fileButton').click(function(){
 $('#upload').trigger("click");
 });
&#13;
.upload{
    display:none
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" name="upload" id="upload" class="upload"/>
<button class="fileButton" id="fileButton">Choose File</button>
<input type="submit" name="button" value="Contact Me" class="supportButton"></input>
&#13;
&#13;
&#13;

答案 4 :(得分:1)

默认情况下type属性为submit,您的表单需要提交,请改为使用type='button'

<button class="fileButton" id="fileButton" type='button'>Choose File</button>
相关问题