简体   繁体   English

停止 <enter> 从IE8中的文件输入提交表单

[英]Stop <enter> from submitting form on file input in IE8

IE8 renders a textbox alongside the browse button for a file input: IE8在浏览按钮旁边呈现文本框以进行文件输入:

<input type="file" />

I understand that there are a number of security constraints regarding what you can do with file inputs using JavaScript but is there a good way to stop the parent form submitting when a user focuses on this textbox and presses enter? 我理解有关使用JavaScript可以对文件输入执行的操作存在许多安全限制,但是当用户关注此文本框并按Enter键时,是否有一种很好的方法可以阻止父表单提交?

I would look at using jQuery's keypress and catching it. 我会看看使用jQuery的keypress并捕获它。 I haven't done this myself to test but have a look here: 我自己没有做过测试,但看看这里:

http://forum.jquery.com/topic/how-to-catch-keypress-on-body http://forum.jquery.com/topic/how-to-catch-keypress-on-body

The simplest way is to simply return false in the onSubmit event handler on the form element. 最简单的方法是在表单元素的onSubmit事件处理程序中返回false。 Presumably, you have a button elsewhere in the form that you want to actually trigger the form submit. 据推测,您希望实际触发表单提交的表单中的其他位置有一个按钮。 On that button, you can add an onclick handler that calls form.submit(). 在该按钮上,您可以添加一个调用form.submit()的onclick处理程序。 When you submit the form programmatically, the onSubmit handler is not fired. 以编程方式提交表单时,不会触发onSubmit处理程序。

Might look something like this: 可能看起来像这样:

<form id="myform" method="post" action="http://yourserver/page" onSubmit="return false;">
    <input id="myfile" type="file" name="file"/>
    <input type="button" value="upload" onClick="submitForm();" />
</form>

<script type="text/javascript">

function submitForm()
{
    // if no file, don't submit
    var file = document.getElementById("myfile");
    if (file.value.length == 0) return;

    var form = document.getElementById("myform");
    form.submit();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM