0

I'm trying to write a JavaScript / jQuery function that is called when a button with the class "add-row" is clicked. The function appends HTML to the DOM that adds another button with the same class. What I want is that when that second button is clicked, the function will be called again and create yet another button, and so on.

Here's the code for the first button:

<div>
    <label for="add_row-0"></label><br>
    <button type="button" class="add-row">Add Another Item</button>
</div>

And here's the JavaScript function:

$(document).ready(function(){
        $(".add-row").click(function(){

          
            $(".add-row").last().after(
                `<div>
                    <label for=${button_identifier}></label><br>
                    <button type="button" class="add-row">Add Another Item</button>
                    </div>
                </div>`
            );
         

        });
 });

This isn't working - what's happening is that the first button works fine and calls the function that creates the second button, but clicking on the second button does nothing.

2 Answers2

1

Use event delegation on the nearest static ancestor of all the <div> containers with the buttons.

$(document).on('click', '.add-row', function(){
    // code here
});

document is used here as an example, but you should replace it with the nearest static ancestor for better performance.

Unmitigated
  • 76,500
  • 11
  • 62
  • 80
0

In your there are 2 things to tell,

1- the .click() function doesn't work on newely appended(injected) elements on the dom, it works only on the rendered elemnts with page load.

2- in order to get your click function to work on newely appended elements, you need to use .on("click") function, so you listen on the document for click. =>

$(document).on(click, ".your-selector", function(){
    // your code here
});

so your code should be like

$(document).ready(function () {
    $(document).on(click, ".add-row", function () {
      $(".add-row")
        .last()
        .after(
          `<div>
               <label for=${button_identifier}></label>
                <br>
                <button type="button" class="add-row">Add Another Item</button>
            </div>`
        );
    });
  });
  • you are right, I did post it then I noticed the other answer, I even did vote up for it. it's just 4 mins apart. what should I do now ? should I delete my answer ? – Mohamed Talaat Mar 31 '23 at 03:42