0

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>

2 Answers 2

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>

Sign up to request clarification or add additional context in comments.

Comments

1

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.