0

I've got some jquery that creates the following when a button is clicked:

<div class="box" id="1">
  <div class="left">Icon<form class="dropzone" action="upload2.php?id=1_1" id="1_1"></form></div>
  <div class="remove"><input type="image" src="images/button-minus.png" class="removethis" id="1__1"></div>
  <div class="right">Image<form class="dropzone" action="upload2.php?id=1_2" id="1_2"></form></div>
  <div class="clear"></div>
</div>

I've also got an 'Add another' button

<div class="addmore">
  <input type="image" src="images/button-plus.png" class="addanother">
</div>

It increments the ids when the 'Add Another' button is pressed but that's not too important here.

<script>
    // when the button is clicked to create 2 more dropzones:
    $(".addanother").click(function () {
      ...
    });

I then have a minus button that can delete it if the user requires. At the moment, I'm just trying to get it to show an alert so I know it's returning the correct box id.

It works for the hard coded first one, but not any I've created from clicking the Add Another button.

$(document).ready(function() {  
    $(".removethis").click(function (event) {
        currentEvent = event.target.id;
        alert(currentEvent);
        //$( ".boxes #"+currentEvent ).remove();
    });
});

Am I missing something to make it realise that the newly created ones exist?

It currently comes up with no error or alert?

jimbeeer
  • 1,308
  • 1
  • 10
  • 22

1 Answers1

1

You need to use event delegation as remove button is generated dynamically:

$("body").on('click','.removethis',function (event) {
    currentEvent = event.target.id;
    alert(currentEvent);
    //$( ".boxes #"+currentEvent ).remove();
});
Milind Anantwar
  • 77,788
  • 22
  • 86
  • 114
  • I knew it was a simple solution, but i didn't know it was called event delegation. Forgive my ignorance. – jimbeeer Mar 09 '15 at 10:49