Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change File Input Label Text to File Name

Tags:

html

jquery

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!

like image 369
Daniel Avatar asked Nov 24 '25 20:11

Daniel


1 Answers

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

like image 187
Jehad Ahmad Jaghoub Avatar answered Nov 27 '25 10:11

Jehad Ahmad Jaghoub



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!