element? I have several checkboxes and an input for uploading files. I would l...">

How to check if a file was selected in the <input type = "file"> element?

I have several checkboxes and an input for uploading files. I would like to turn on the button again if one or more of the checkboxes is marked AND, if the input value is not null.

Here is the link for bootply

Here is my html

<div class="upload-block">
    <input type="checkbox">
    <input type="checkbox">
    <input type="checkbox">
    <input type="file" id="InputFile">
    <button id="upload-btn" type="button blue-button" 
            class="btn blue-button" disabled>Submit</button>

</div>

Here is my javascript starting point: Updated via Karl Bind the event changeto all inputs and then use some condition:

  $('.upload-block input').change(function() {
    $('#upload-btn').prop(
        'disabled',
        !($('.upload-block :checked').length && $('#InputFile').val()));
  });

Example

This works for all checkboxes, but #InputFilehas a value other than none. those. where is the file selected. However this does not work in IE9

How can I update this to work in IE9?

+4
source share
5

change , :

  $('.upload-block input').change(function() {
    $('#upload-btn').prop(
        'disabled',
        !($('.upload-block :checked').length && $('#InputFile').val()));
  });

+10

:

if($('#InputFile').val().length){
//do your stuff
}

, $.trim(), () :

if($.trim($('#InputFile').val()).length){
//do your stuff
}
+6

Pure JS:

<input type="file" id="InputFile">
<button onclick="buttonSubmitClicked(event)">Submit</button>

<script>
    function buttonSubmitClicked(event) {

        if (!document.getElementById("InputFile").value) {
            event.preventDefault();
            alert("Please choose a file!");
        } else {
            alert("File've been chosen");
        }
    }
</script>

jsfiddle:

+4

. , .

$('#InputFile, .upload-block :checkbox').change(function(){
   var isValid= $('.upload-block :checkbox:checked').length  && $('#InputFile').val();
   $('#upload-btn').prop('disabled',isValid);
});
+1
  $('.upload-block input').change(function() {
        if ($('.upload-block :checked').length && $('#InputFile').val() ) {

          $('#upload-btn').prop('disabled',false);
        }
        else {
          $('#upload-btn').prop('disabled',true); 
        }
         });

. , ,

+1

All Articles