0

I have the following HTML to start with :

    <div id="p_scents">

       <p>
          <label for="p_scnts">Friend n°1</label>
          <input type="text" id="p_scnt" size="20" name="name_0" class="form-control" placeholder="Name of your friend" />
          <input type="text" id="p_scnt address-input-0" class="form-control" name="address_0" placeholder="Their location"/>
       </p>
    </div>

    <button id="addScnt" type="button">Add a friend</button>

I want to add some extra inputs with jQuery, which I succeed to do thanks to the following script:

$(function() {
        var scntDiv = $('#p_scents');
        var i = $('#p_scents p').length + 1;

        $('#addScnt').click(function() {
                $('<p><label for="p_scnts">Friend n°' + i +'</label><input type="text" id="p_scnt" size="20" name="name_' + (i-1) +'" class="form-control" placeholder="Name of your friend" /><input type="text" id="p_scnt address-input-' + (i-1) +'" class="form-control" name="address_' + (i-1) +'" placeholder="Their location"/> <button id="remScnt" type="button">Remove friend</button>').appendTo(scntDiv);
                i++;
                console.log(i);
                return false;
        });

        $('#remScnt').click(function() { 
                if( i > 2 ) {
                        $(this).parent('p').remove();
                        i--;
                }
                return false;
        });

});

My first piece of code, that checks the click on the #addScnt element and appends a new element on the div, works like a charm.

However, my second piece of code, that checks the click on the #remScnt element and should remove its parent <p> element, doesn't work at all and I can't figure out why. I tried debugging with console.log() but I fail... Any clue would be so much appreciated!

  • Possible duplicate of [Event binding on dynamically created elements?](https://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) – showdev Jun 13 '18 at 22:45

1 Answers1

2

Since remScnt is dynamic you need to delegate click, replace this line:

 $('#remScnt').click(function() { 

With this one:

 $(document).on('click','.remScnt',function() { 

BTW, ids has to be unique, make sure to replace id with class instead.

<button class="remScnt"