santa santa - 5 months ago 38
jQuery Question

disable submit button until file selected for upload

I have a form for uploading images. I'd like to disable submit button, until user selects an image to upload. I'd like to do it with jQuery. Currently I have a JavaScript 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
<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">


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


                if ($(this).val()) {
                    // or, as has been pointed out elsewhere:
                    // $('input:submit').removeAttr('disabled'); 


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

Demo at JS Fiddle.