disable submit button until file selected for upload
If anyone is looking at this now (in 2021), this is the non-jquery solution I was able to come up with!! Some of this won't work with older browsers, so your mileage might vary- but if you're looking for a modern simple solution- this should be more than fine.
<div>
<form method="post" action="someAction" enctype="multipart/form-data">
<input type="file" name="fileUploaded" />
<input type="submit" disabled="true" />
</form>
<script>
document.querySelector("input[type=file]").onchange = ({
target: { value },
}) => {
document.querySelector("input[type=submit]").disabled = !value;
};
</script>
</div>
Some notes about this solution: onChange
takes a function that returns an object event
, which has target
and in there value
. value
is the string of the file name uploaded, and returns empty string when a user cancels the selection.
If you're looking for a solution that works with multiple file inputs and submissions, you can use class names to grab the right one.
<!-- index.html -->
<div>
<form
method="post"
action="someAction"
enctype="multipart/form-data"
>
<input class="fileUpload1" type="file" name="fileUploaded" />
<input class="fileUpload1" type="submit" disabled="true" />
</form>
</div>
<div>
<form
method="post"
action="someOtherAction"
enctype="multipart/form-data"
>
<input class="fileUpload2" type="file" name="fileUploaded2" />
<input class="fileUpload2" type="submit" disabled="true" />
</form>
</div>
// script.js
document.querySelectorAll("input[type=file]").forEach(
(fileInput) =>
(fileInput.onchange = ({ target: { value } }) => {
document.querySelector(
`input[type=submit].${fileInput.className}`
).disabled = !value;
})
);
Try
$('#my_uploader').change(function() {
if($(this).val()) {
$('#my_submit_button').attr('disabled', '');
} else {
$('#my_submit_button').attr('disabled', 'disabled');
}
});
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.
Slightly simpler way using prop() which I think is the preferred way to do it now:
$('input:file').on("change", function() {
$('input:submit').prop('disabled', !$(this).val());
});
Tested in IE, Chrome and FireFox.