3

I am trying to change the label text for a file input field to the name of the file, however I get the following error in my console:

Uncaught TypeError: Cannot read property 'files' of undefined

Here's the HTML and JQuery:

<div class="custom-file">
    <label class="custom-file-label text-left" for="customFile" id="file">Choose file</label>
    <input type="file" class="custom-file-input" id="customFile">
</div>


<script type="text/javascript">
    $('#customFile').change(function() {
      var i = $(this).prev('label').clone();
      var file = $('customFile')[0].files[0].name;
      $(this).prev('label').text(file);
    });
</script>

I'm still learning JQuery, so any help is greatly appreciated!

1 Answer 1

3

i think you just forget # for customFile on selector

 var file = $('#customFile')[0].files[0].name;

here full code

 $('#customFile').on("change",function() {
      console.log("change fire");
     var i = $(this).prev('label').clone();
      var file = $('#customFile')[0].files[0].name;
   console.log(file);
      $(this).prev('label').text(file);

    });

https://codepen.io/jehadja/pen/pLrYwq?editors=1111

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! Not going to lie, I spent several minutes trying to figure this simple thing out.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.