I’m using jQuery to let users dynamically add and remove form fields, but it’s not working properly.
It works perfectly fine when removing the first field (which is hard-coded in the HTML mark-up), but it won’t let me remove any of the fields that have been added dynamically.
Here’s my jQuery code:
$("#addDog").click(function(event)
{
event.preventDefault();
var doglist = <?php echo "'" . $javadogs . "'"; ?>;
var newdog = '<div><select name="resDog[]" class="select">' + doglist + '</select><input type="text" class="shortinput" name="resResult[]" size="20" value="" /><a href="#" class="deleteDog"><img src="/admin/images/delete.png" alt="Remove dog" /></a></div>';
$(this).parent().before(newdog);
});
$(".deleteDog").click(function(event)
{
event.preventDefault();
$(this).parent().remove();
});
I tried using jQuery’s .on() function, but that didn’t work either.
Here’s how you want to use
onIdeally all of these
deleteDogbuttons will be housed in some sort of container. If all of these buttons were to be in a div with an id offoo, you would more efficiently set up the events like this:Now, instead of every click anywhere in the document being inspected, only those clicks that bubble up to
#fooare.I’m guessing you originally tried to use
onlike this:This is functionally identical to saying:
Omitting the selector parameter like this creates a directly-bound event—only the elements that match the
.deleteDogselector at the timeonis called will be wired.Applying a selector—like in my original code—makes it a delegated event—jQuery will listen for all clicks, and if they originate from an element with the class
deleteDog, the function will fire.