Skip to content
Advertisement

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>

Advertisement

Answer

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>
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement