Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
599 views
in Technique[技术] by (71.8m points)

jquery - disable submit button until file selected for upload

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.

Here's what I've got now:

<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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

jQuery

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

Demo at JS Fiddle.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...