0

I'm trying create a list of Messages a user can type in an textarea on the site and delete any of them using a button he automatically creates with each message. My idea is that I create a div in which I first put the message of the user in and then prepend the button with the same ID of the div; This way I call the ID of the button and remove all elements with the same ID.

<script>
var theButtonId = 1;
$(document).ready(function() {
$('#commentButton1').click(function() {
    var toAdd = $("textarea#commentTextarea1").val(); //Content to add
    var theId = "dieButtons"+theButtonId.toString(); //creating unique ID

    // Adding first Div      
    $('#targetField').append( 
        $('<div />', {
            id: theId,
            }));
    // Adding content
    $('#'+theId).append(
        $('<div />', {
             text: toAdd
             }));
    //(-----1-----)Adding Button        
    $('#'+theId).prepend(
         $('<button />', {
             type: 'button',
             id: theId,
             class: 'commentButton2',
             text: "-"
             }));
    theButtonId++;
    });
});
//Button Command
$(document).on("ready", function(){
  //(-----2-----)
$('.commentButton2').on("click", function(){  
   var thisId = $(this).attr("id");
       $("#"+thisId).remove();
});
});
</script>

It perfectly lists the elements in the #textfield I added a button directly in my HTML code which deletes certain divs, as well as itself using the code above. This is why I know that the Problem is that the created Buttons at (-----1-----) don't react to the command in (-----2-----)

I already tried to create an Input of type button and put a .click function instead of .on("click", [...]).

sankai
  • 7
  • 3

2 Answers2

1
$(document).on('click', '#buttonid', function() {

});

Use event delegation on dynamically created elements

DOCUMENTATION

guradio
  • 15,524
  • 4
  • 36
  • 57
  • Ah, now I see! It worked finde, thanks! – sankai Sep 10 '15 at 11:54
  • 1
    Thanks a lot guradio. That helped for me too. Eventough, this scenario of dynamic list is very frequent, I have hard time finding a decent bootstrap documentation about this kind of details on how to use bootstrap elements (different scenarios, events, examples, ...)? – AJN Mar 18 '18 at 05:39
0

Working fiddle

Try to use :

$('#targetField').on("click",'.commentButton2', function(){  

Instead of :

$('.commentButton2').on("click", function(){ 

It should work.

Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
  • 1
    It didn't work for me and even blocked the static created buttons.. But got an answer from Pekka, thanks :) – sankai Sep 10 '15 at 11:56