I don’t need to be able to add multiple files to a page, and the code generally works. But the block that is dynamically created, it no longer works.

$('.block-file input[type="file"]').change(function(){ $(this).prev().addClass("del"); $(this).prev().removeClass("add"); $(this).prev().find("span").text($(this).val()); $(this).prev().attr('onclick', '$(this).parent().remove();') $(this).parent().parent().append('<div class="block-file"><a class="add" onclick="$(this).next().click();"><i class="fa fa-plus-circle"></i><span>Вы можете добавить фото</span></a><input type="file" style="visibility:hidden;width: 0;"></div>'); }); 

HTML

 <div class="block-file"> <a class="add" onclick="$(this).next().click();"><i class="fa fa-plus-circle"></i><span>Вы можете добавить фото</span></a> <input type="file" style="visibility:hidden;width: 0;"> </div> 
  • Pasha, tell me, have I edited your text correctly (has your intentions been correctly conveyed)? - Vadim Ovchinnikov

2 answers 2

Because the DOM model is already loaded into the browser, you cannot change the newly created objects dynamically (they are simply not loaded). To solve the problem you need to use

 $('body').on('change', '.block-file input[type="file"]', function(){ //... весь код тут }); 

Learn more http://api.jquery.com/on/

  • 3
    @ Pasha "Thank you very much" is expressed here by the accepted answer :). - Vadim Ovchinnikov

Instead

 $('.block-file input[type="file"]').change(function(){ 

use

 $(document).on("change", '.block-file input[type="file"]', function(){