禁用提交按钮,直到选择要上传的文件 [英] disable submit button until file selected for upload

查看:27
本文介绍了禁用提交按钮,直到选择要上传的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个上传图片的表格.我想禁用提交按钮,直到用户选择要上传的图像.我想用jQuery来做.目前我有一个 JavaScript 函数,通过在提交时禁用它来防止用户多次提交表单.将此功能与新功能结合起来会很好.

I have a form for uploading images. I'd like to disable the submit button, until user selects an image to upload. I'd like to do it with jQuery. Currently I have a JavaScript function that prevent user from submitting the form more than once by disabling it on submit. It'd be nice to combine this functionality with the new one.

这是我现在所拥有的:

<script type="text/javascript">
function submitonce(theform) {
    //if IE 4+ or NS 6+
    if (document.all || document.getElementById) {
        //screen thru every element in the form, and hunt down "submit" and "reset"
        for (i = 0; i < theform.length; i++) {
            var tempobj = theform.elements[i]
            if (tempobj.type.toLowerCase() == "submit" || tempobj.type.toLowerCase() == "reset")
            //disable em
            tempobj.disabled = true
        }
    }
}
</script>
<form name="form" enctype="multipart/form-data" method="post" action="upload.php" onSubmit="submitonce(this)">
 <input type="file" name="my_field" value="" />
 <input type="submit">
</form>

推荐答案

以下似乎在 Chrome 和 Firefox (Ubuntu 10.10) 中可靠运行,我目前无法在其他平台上检查:

The following seems to work reliably in Chrome and Firefox (Ubuntu 10.10), I'm unable to check on other platforms at the moment:

$(document).ready(
    function(){
        $('input:file').change(
            function(){
                if ($(this).val()) {
                    $('input:submit').attr('disabled',false);
                    // or, as has been pointed out elsewhere:
                    // $('input:submit').removeAttr('disabled'); 
                } 
            }
            );
    });

html

<form action="#" method="post">
    <input type="file" name="fileInput" id="fileInput" />
    <input type="submit" value="submit" disabled />
</form>
<div id="result"></div>

JS Fiddle 演示.

这篇关于禁用提交按钮,直到选择要上传的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆