Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display file name for custom styled input file using jquery?

I have styled a file input using CSS:

.custom-file-upload {    border: 1px solid #ccc;    display: inline-block;    padding: 6px 12px;    cursor: pointer;   }
<form>    <label for="file-upload" class="custom-file-upload">      <i class="fa fa-cloud-upload"></i> Upload Image    </label>    <input id="file-upload" name='upload_cont_img' type="file" style="display:none;">  </form>  

Everything is working fine, but I’d like to display the selected file name. How is this possible using CSS or jQuery?

like image 298
amM Avatar asked Jan 09 '17 07:01

amM


People also ask

How check file is selected or not in jQuery?

length property in jQuery to check the file is selected or not. If element. files. length property returns 0 then the file is not selected otherwise file is selected.

What is the value of input type file?

A file input's value attribute contains a string that represents the path to the selected file(s). If no file is selected yet, the value is an empty string ( "" ). When the user selected multiple files, the value represents the first file in the list of files they selected.


1 Answers

You have to bind and trigger the change event on the [type=file] element and read the files name as:

$('#file-upload').change(function() {    var i = $(this).prev('label').clone();    var file = $('#file-upload')[0].files[0].name;    $(this).prev('label').text(file);  });
.custom-file-upload {    border: 1px solid #ccc;    display: inline-block;    padding: 6px 12px;    cursor: pointer;  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>  <form>    <label for="file-upload" class="custom-file-upload">      <i class="fa fa-cloud-upload"></i> Upload Image    </label>    <input id="file-upload" name='upload_cont_img' type="file" style="display:none;">  </form>
like image 87
Jai Avatar answered Oct 02 '22 20:10

Jai