0

I am appending a small block of code that has inside of it an image that when clicked triggers a click event on the input for file uploading. When the page is loaded and/or refreshed, there is only one block that once changed, fires the event to append a new one.

<div class="add_new_image">
    <div class="img">
        <div class="file-upload-trigger">
            <input type="file" name="imagem[]" class="none file-chooser" required/>
            <img class="more" src="/assets/auto/images/add_image.png"/>
        </div>
    </div>
</div>

The JQuery code for appending:

$('#novo_anuncio .file-chooser').change(function() {
    readURL(this);
    $('#novo_anuncio .add_new_image').append(
        '<div class="img">\n\
            <div class="file-upload-trigger">\n\
                <input type="file" name="imagem[]" class="none file-chooser" required/>\n\
                <img class="more" src="/assets/auto/images/add_image.png"/>\n\
            </div>\n\
        </div>');
});

The problem is that the appended code does not trigger the click event on the input. The code is identical and it is appended correctly inside of the .add_new_image main tag. What could be wrong?

1 Answers1

0

You need to use .on() because when you are binding the "change" listener, your new ".file-chooser" doesn't exist. jQuery on handles all that for you.

Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time.

$('body').on('change', '#novo_anuncio .file-chooser', function() {
    readURL(this);
    $('#novo_anuncio .add_new_image').append(
        '<div class="img">\n\
            <div class="file-upload-trigger">\n\
                <input type="file" name="imagem[]" class="none file-chooser" required/>\n\
                <img class="more" src="/assets/auto/images/add_image.png"/>\n\
            </div>\n\
        </div>');
});

$('body').on('change', '#novo_anuncio .file-chooser', function() {
    alert("change");
    $('#novo_anuncio .add_new_image').append(
        '<div class="img">\n\
            <div class="file-upload-trigger">\n\
                <input type="file" name="imagem[]" class="none file-chooser" required/>\n\
                <img class="more" src="/assets/auto/images/add_image.png"/>\n\
            </div>\n\
        </div>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="novo_anuncio">
  <div class="add_new_image">
    <div class="img">
        <div class="file-upload-trigger">
            <input type="file" name="imagem[]" class="none file-chooser" required/>
            <img class="more" src="/assets/auto/images/add_image.png"/>
        </div>
    </div>
  </div>
</div>
Marcos Casagrande
  • 37,983
  • 8
  • 84
  • 98