How do I check if a file has been selected in a <input type=“file”> element?

南笙酒味 提交于 2020-12-29 05:51:57

问题


I have multiple checkboxes and a file upload input. I would like to re-enable a button if one or more checkbox's are checked AND if the input value is not null.

Here is a link to bootply

Here 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 a change event on all input 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 the checkboxes and #InputFile has a value other than none. i.e. where a file has been chosen. However this does not work in IE9

How can I update this to work in IE9?


回答1:


Bind a change event on all input and then use some condition:

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

Example




回答2:


Like this:

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

You can better use by using $.trim() method not to allow (trim) spaces:

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



回答3:


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: check it out




回答4:


I would apply the validation to all elements involved. This way changing either the checkboxes or the input will update disabled

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



回答5:


  $('.upload-block input').change(function() {
        if ($('.upload-block :checked').length && $('#InputFile').val() ) {

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

No need of separate selectors for checkbox and input file .upload-block input is enough to catch catch both the checkbox and file value change



来源:https://stackoverflow.com/questions/24828066/how-do-i-check-if-a-file-has-been-selected-in-a-input-type-file-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!