Ankerstjerne
Ankerstjerne

Reputation: 122

Checking if an input file has been selected?

I am currently working on a website, where you are able to upload a file:

<input type="file" name="file" id="file" class="form-control" />

I then have a button which you can press to upload the selected file:

<button class="btn btn-primary" type="submit">Upload CV</button>

Here I would like the button to be clickable ONLY if a file has been selected. Is this possible using JS, and how?

Thanks in advance!

Upvotes: 3

Views: 5952

Answers (3)

joalcego
joalcego

Reputation: 1156

You can use JQuery as FullOfQuestions said, but it would be also good to verify that the file was selected before executing button code!

<input type="file" name="file" id="myFile"/>

<!--Add disabled attribute to the button so that is appears disabled at page load-->
<button id="myBtn" type="submit" disabled>Upload CV</button>

<script type="text/javascript">
        $(function () {

            //when input's value changes
            $("#myFile").change(function () {
                if($(this).val())
                {
                    $("#myBtn").prop("disabled", false);
                }
                else
                {
                    $("#myBtn").prop("disabled", true);
                }
            });

            //when button is clicked
            $("#myBtn").click(function () {
                if($("#myFile").val())
                {
                    console.log("file selected");
                }
            });
        });

</script>

Upvotes: 2

boombox
boombox

Reputation: 2456

You can do this with native JS below. The button is enabled when a file has been selected, but if a file has not been selected, the button is disabled.

var button = document.querySelector('button[type=submit]');

button.disabled = true;

document.getElementById('file').addEventListener('change', function () {
  if (this.value.length > 0) {
    button.disabled = false;
  } else {
    button.disabled = true;
  }
});
<input type="file" name="file" id="file" class="form-control" />

<button class="btn btn-primary" type="submit">Upload CV</button>

Upvotes: 1

Aman Gupta
Aman Gupta

Reputation: 1874

Using 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'); 
            } 
        }
        );
});

Add disabled attribute in button tag.

Upvotes: 2

Related Questions