0

I am new to JavaScript an I have a basic set up where I can append a div with another div. I am trying to create a button that lets me remove those divs that are added dynamically, these are the two functions:

$("#add_new").click(function(){
event.preventDefault();
clicks += 1;
if (clicks < 10)
{
    //document.getElementById("total_steps_count").innerHTML = clicks;
    $("#steps").append('<div id="remove"><input type="text" id="step_title" class="form-control" name="step_title[]" placeholder="Enter a title for this step"><br><input type="file" id="step_image" name="step_image[]" ><br><input type="text" class="form-control" id="step_caption" name="image_caption[]" placeholder="Enter a caption for this image"><br><input type="text" id="step_text" name="step_text[]" class="form-control" placeholder="Walk us through this step"><br><button class="btn btn-default" id="remove_step"><i class="fa fa-times"></i> Remove This Step</button></div><br><br><hr>')
}
else
{
    alert("The maximum number of allowed steps is 10");
}
});



//Remove step
$("body").on("click", "#remove_story_step", function(){
    event.preventDefault();
    clicks -= 1;
    $(this).closest("#remove_story").remove()
});

When the 'add_new' button is clicked, the div is properly appended to the target div, however when I click the 'remove_step' button, the page refreshes and all of the previously appended divs are gone.

Like I say I am new to JavaScript/jQuery so I'm not sure how I can debug this, any help would be greatly appreciated!

Aaranihlus
  • 143
  • 2
  • 13
  • 2
    You need to use a delegated event handler as you're appending the content after the page has been loaded. See the question I marked as a duplicate for more information. Also note that you really should not put `id` attributes in the content you add to the page, as this will end up duplicating them, which will also be a problem. Change those to classes instead – Rory McCrossan Feb 03 '17 at 10:26
  • Hi Rory, I have updated my OP with a working solution, thank you very much for the link, it proved very useful – Aaranihlus Feb 03 '17 at 12:14

0 Answers0