<script type="text/javascript"> window.onload = function(){ document.getElementsByTagName('input')[0].onchange = function(){ document.getElementsByTagName('div')[0].innerHTML = this.value; }; }; </script> <input type="file" /> <div></div> 

In this javascript script, a script is made that displays the full path of the file. How to fix to show only the file name?

    2 answers 2

    Inputs with file type have a collection of selected files , it stores objects of type File , which has a name field that contains the name of the selected file.

     document.getElementsByTagName('input')[0].onchange = function() { if (this.files[0]) // если выбрали файл document.getElementsByTagName('div')[0].innerHTML = this.files[0].name; }; 
     <input type="file" /> <div></div> 

      We look the answer from @Grundy.


      Javascript

       document.querySelector('input').addEventListener('change', function() { var splittedFakePath = this.value.split('\\'); document.querySelector('div').textContent = splittedFakePath[splittedFakePath.length - 1]; }); 
       <input type="file"> <div></div> 

      https://jsfiddle.net/xfynp30o/


      jQuery

       $('input').on('change', function() { var splittedFakePath = this.value.split('\\'); $('div').text(splittedFakePath[splittedFakePath.length - 1]); }); 
       <script src="//ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <input type="file"> <div></div> 

      https://jsfiddle.net/pxk8x599/


      Regular Expression Option

      You can add problems and do it with regular expressions:

       document.querySelector('input').addEventListener('change', function() { document.querySelector('div').textContent = this.value.replace(/.*\\(.+)/, '$1'); }); 
       <input type="file"> <div></div> 

      https://jsfiddle.net/bvk7xcw4/