0

I am using the example from here: How to add a button dynamically using jquery

What I would like to know, is how can I add jquery function on the new buttons that are created after I clicked on insert after?

Let's say I have clicked twice the button, insert after and so I have these new two buttons. How can I add functions on the buttons?

What I would like to recreate is: `

<!DOCTYPE html>
<html>

  <head>
    <link rel="stylesheet" href="style.css">
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> 
  </head>

  <body>
<button id = "btn_add> Add </button>  
   <div id= "container">
  <div id = "under_container"> 
 
 </div>
   </div>
  </body>

</html>`

JS

$(document).ready(function () {
 $("#btn_add").click(() => {
        $('#container').append(`<div id="text">\
        <div id="title" >\
          Trial
        </div> \
        <button id="btn_addOther"> Add Other </button>
        </div>`); 
    })


 $("#btn_addOther").click(() => {
 $('#under_container').append(`<div id="card"> \
        <textarea placeholder="Title" type="text" >Title</textarea> \
        </div>`
        );
    });
});

So, I would like to create a button that adds other buttons and when the new buttons are created, they should be able to create other things on the page.

2 Answers2

0

To achieve your goal there's two issues to solve. Firstly as you're duplicating the content you need to change the HTML to use class attributes instead of id, as you cannot duplicate the same id multiple times in the same DOM.

The second issue is that because some elements are added to the DOM after the page has loaded you need to use a delegated event handler.

$(document).ready(function() {
  $(document).on('click', '.btn_add', () => {
    $('#container').append(`<div class="text"><div class="title">Trial</div><button class="btn_addOther">Add Other</button><div></div>`);
  });


  $(document).on('click', '.btn_addOther', () => {
    $('#under_container').append(`<div class="card"><textarea placeholder="Title" type="text" >Title</textarea></div>`);
  });
});
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<button class="btn_add"> Add </button>
<div id="container">
  <div id="under_container"></div>
</div>
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
0

try to use $('body').on('click', "#btn_addOther", function () {...})

andrei040191
  • 408
  • 4
  • 7