1

I am doing my upload file page , and i have a page that have an <input> where the user can write a name for his file and another <input> where the user will chose a file.

What i want to do is , after the user selects a file , the input with the name to automatically get filled with the file name ( without extension ).

My html code looks like that

<div class="card-header text-center" data-background-color="rose" style="margin-left: 15px;">
     <h3 class="card-title">Upload file</h3>
</div>
<div class="card-content">
     <div class="input-group">
         <span class="input-group-addon"></span>
    
      <div class="form-group label-floating">
           <label class="control-label"><h4>Chose a name</h4></label><br>
           <input type="text" name="name" id="name" class="form-control" value="" required>
     </div>
    
     <div class="form-group label-floating">
           <label class="control-label"><h4>Choose a file</h4></label><br>
           <input type="file" id="file" name="file" required>
     </div>
</div>
</div>

And i want it to get filled right after i chose the file, as i am doing that on a object oriented programming and i can't reload the page as i have csrf. I want after i get the name , the to get filled with the name of the uploaded file.

2 Answers2

3

Adding this should do what you want, It would be easier in JQuery but as you specified javascript I kept it all pure JS.

<script>
    file.onchange = function(e) { 
        //Get the file path
        var fileName = document.getElementById("file").value; 
        //Get the filename
        var fileName2 = fileName.replace(/^.*[\\\/]/, '');
        //Remove the extension and set the input text
        document.getElementById("name").value = fileName2.replace(/\.[^/.]+$/, ""); 
    };
</script>
omeanwell
  • 1,847
  • 1
  • 10
  • 16
0

I have updated your code and do let me know if need some clarification

    <div class="card-header text-center" data-background-color="rose" style="margin-left: 15px;">
         <h3 class="card-title">Upload file</h3>
    </div>
    <div class="card-content">
         <div class="input-group">
             <span class="input-group-addon"></span>
        
          <div class="form-group label-floating">
               <label class="control-label"><h4>Chose a name</h4></label><br>
               <input type="text" name="name" id="name" class="form-control" value="" required>
         </div>
        
         <div class="form-group label-floating">
               <label class="control-label"><h4>Choose a file</h4></label><br>
               <input type="file" id="file" name="file" onchange="getFileData(this);" required>
         </div>
    </div>
    </div>

<script type="text/javascript">
function getFileData(myFile){
   var file = myFile.files[0];  
   document.getElementById("name").value = file.name;
}
</script>
Sourabh
  • 157
  • 2
  • 12