Which button is clicked?

I had this question after viewing Duplicating DIVs and nested elements.

Building on Julian's answer for cloning my DIV, I also added a Clear File button, as follows
            <div id="divAttachNew">
                
                <label class="lblAutoWidth">
                    <span class="fa fa-paperclip"></span>
                    Attach New Files</label>
                <span>(maximum file size: <?php echo $env['upload_size_mb']; ?> MB)</span>
                
                <div id="divAttachFiles">
                                        
                    <input type="file" id="file[]" name="file[]" class="attachFile">                    
                    <input type="button" class="btnClearFile" 
                           id="btnClearFile[]" name="btnClearFile[]" value="Clear File">
                    
                </div>

            </div>            


        <div id="divAttachAdditional">
            <span class="fa fa-plus-circle"></span>
            <a id="aAddFiles">Attach Additional files</a>
        </div>

Open in new window


And my jQuery is
    $('#aAddFiles').on('click', function(e){
        e.preventDefault();
        $('#divAttachNew').append($('#divAttachFiles').clone());
    });
      
    $('.btnClearFile').on('click', function(){
       
        console.log($(this));
        
    });

Open in new window


So now I have 2 questions.

1- When clicking #btnClearFile, only the first button produce output, the others do not. Why?

2- How  would I determine which  of thhese buttons is clicked, and would remove that corresponding DIV?

Thank you.
APD TorontoAsked:
Who is Participating?
 
Jan LouwerensSoftware EngineerCommented:
Html element ids should be unique within the DOM. If your duplicating sections, you should probably be using classes instead of ids, to prevent duplicate ids.

The reason only the first one is producing output is because that's the only one in that exists in the DOM at the time the click event is bound. If you want to be able to target dynamically generated elements, you'll need to use a diffferent form of 'on'. try:

$(body).on('click', '.btnClearFile', function(e){
       
        console.log($(this));
        console.log('event.target: %o', e.target);
        
    });

Open in new window



Either 'this' or the event target will be the element that was clicked. From there, you can use jQuery to find the nearest parent (or ancestor) that you want to remove from the DOM.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.