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", [...]).