Jack
Jack

Reputation: 31

HTML and Javascript detect if input contains a file?

Hello I have the following code that allows the user to select a file and upload it to the server:

 <form action="postphp.php" method="post" enctype="multipart/form-data">

         <input id="videoage" type="file" name="video" style="margin-left:-242px;margin-top:10px;opacity:0;">
         <label for="videoage" id="labelvideo">Choose Video...</label>
 </form>

It works great but when the user selects a file I want the 'choose video...' text on the input to change to 'example.mp4'. Is this possible using javascript if so how can I do that? Thanks.

Upvotes: 0

Views: 140

Answers (1)

jayantish
jayantish

Reputation: 454

You can write in your script:

 jQuery(function($) {
  $('input[type="file"]').change(function() {
    if ($(this).val()) {
      var filename = $(this).val().split('\\').pop();
      $(this).closest('.file-choose').find('.file-name').html(filename);
    }
  });
});

where file-choose and file_name are the classes added in your <form> and <label> respectively.
Please check the snippet here.

Upvotes: 1

Related Questions