How to disable submit button until file is selected
I have an HTML file upload page and I need the submit button to be disabled until a file is selected. Then the submit button will be enabled and the user can upload. I assume I can use jQuery code to query the file upload field's value to see whether a file has 开发者_Python百科been selected to upload. And I assume I can check that whenever focus has left the file upload field. My concern is that some browsers might act funny with this and then my users can't upload any files.
Is there a safe way to do this, preferably using jQuery, where I won't be in danger of having some users unable to upload?
This jQuery should work, and is tied to the file input's change()
event. This code also applies the disabled
attribute so, in the event the user has JavaScript disabled, it shouldn't prevent the form being used:
$(document).ready(
function(){
$('input:submit').attr('disabled',true);
$('input:file').change(
function(){
if ($(this).val()){
$('input:submit').removeAttr('disabled');
}
else {
$('input:submit').attr('disabled',true);
}
});
});
JS Fiddle demo.
A simpler way is to check the file field when the user actually submits the form... that way you won't have to look for form changes.
$(function() {
$('form').submit(function() {
if(!$("form input[type=file]").val()) {
alert('You must select a file!');
return false;
}
});
});
This code is Unobtrusive JavaScript and it won't mess up the form if the user does not support JS.
David Thomas's code can be set for button ID:
<script type="text/javascript">
$(document).ready(function () {
$('#<%=btInsert.ClientID %>').attr('disabled', true);
$('input:file').change(
function () {
if ($(this).val()) {
$('#<%=btInsert.ClientID %>').removeAttr('disabled');
}
else {
$('#<%=btInsert.ClientID %>').attr('disabled', true);
}
});
});
</script>
精彩评论