marcsimm marcsimm - 6 months ago 39
Javascript Question

Make button disabled if input type file is empty in bootstrap

I have form where the user can upload a file but I want the upload button to be disabled if the input type file does not contain a file how do I do that ?

<form action="/upload" method="post" enctype="multipart/form-data">
<div class="form-inline">
<div class="form-group">
<input type="file" name="fileUploaded">
</div>
<button type="submit" class="btn btn-sm btn-primary">Upload file</button>
</div>
</form>

Answer

you should add attribute disabled to the button

<button type="submit" class="btn btn-sm btn-primary" disabled>Upload file</button>

then we will watch changes with the code to enable the button when the input type file contain any file

$('input[type=file]').change(function(){
    if($('input[type=file]').val()==''){
        $('button').attr('disabled',true)
    } 
    else{
      $('button').attr('disabled',false);
    }
})

Demo here : https://jsfiddle.net/IA7medd/08eekkbt/