Get Selected Filename in dynamic input file fields using jQuery/JavaScript

I have dynamic input type file fields which can be added more by clicking on add more

I have scripted to get file name when it is selected, but it is working for only first field not for other fields.

So how to get all file names when it is selected?

$("#em_add").click( function(){
			var decoration_box = $(".one").html();
			$(".logos").append('<div class="one">'+decoration_box+'</div>');
});

$('.logo').change(function () {
	var filePath=$(this).val(); 
	alert(filePath);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="em_add">Add New</button>
<div class="logos">

  <div class="one">
    <input type="file" name="logo[]" id="logo" class="logo" />
  </div>
  
</div>

8 thoughts on “Get Selected Filename in dynamic input file fields using jQuery/JavaScript”

  1. you are adding elements dynamically but when you add you are not attaching an event handler to these new elements. To fix this you can use event delegation, by attaching the event to parent .logos.

    $("#em_add").click( function(){
    			var decoration_box = $(".one").html();
    			$(".logos").append('<div class="one">'+decoration_box+'</div>');
    });
    
    $('.logos').on('change', '.logo', function () {
    	var filePath=$(this).val(); 
    	alert(filePath);
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <button id="em_add">Add New</button>
    <div class="logos">
    
      <div class="one">
        <input type="file" name="logo[]" id="logo" class="logo" />
      </div>
      
    </div>
    Reply
  2. May I ask why you have added name = "logo[]" like this in the input tag in the below line?

    <input type="file" name="logo[]" id="logo" class="logo" />
    

    Also I am trying to get all filenames.

    Can you please tell me how that is possible?

    Reply
  3. Refer Jquery .on('change') not firing for dynamically added elements

    $("#em_add").click( function(){
    			var decoration_box = $(".one").html();
    			$(".logos").append('<div class="one">'+decoration_box+'</div>');
    });
    
    $('.logos').on('change', 'input:file', function () {
    	var filePath=$(this).val(); 
    	alert(filePath);
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <button id="em_add">Add New</button>
    <div class="logos">
    
      <div class="one">
        <input type="file" name="logo[]" id="logo" class="logo" />
      </div>
      
    </div>
    Reply

Leave a Comment