Reputation: 2636
Hee!
I'm trying to make a script that's adding en removing parts to a fieldset https://jsfiddle.net/3kcoxsac/2/
Now the adding part is working perfectly, only the remove part is just working on the first div and not on the newly added
the html:
<fieldset class="p-bottom-12 bg-white p-around-12 m-bottom-60 u-border-radius">
<div id="js-artist" class="table u-border-box">
<div class="js-artist u-flex-row p-top-12 u-border-top">
<input class="m-left-24 small m-right-24 form-input w-100 cell-10 u-flex u-break" type="text" id="artiestNaam" placeholder="Artiest naam"><input class="form-input small m-right-24 w-100 cell-10 u-flex u-break form-error" type="url" id="artiestURL" placeholder="Artiestenpagina of website"><span class="js-removeArtist cell-w40 large cell-lineheigt u-pointer secondary_color-fixed"><i class="fa fa-trash-o" aria-hidden="true">R</i></span>
</div>
</div>
<span id="js-addArtist">add</span>
</fieldset>
The jquery:
var artist = $('#js-artist'),
i = 1;
$('#js-addArtist').click(function() {
$('<div class="js-artist u-flex-row p-top-12 u-border-top"><input class="m-left-24 small m-right-24 form-input w-100 cell-10 u-flex u-break" type="text" id="artiestNaam_' + i + '" placeholder="Artiest naam"><input class="form-input small m-right-24 w-100 cell-10 u-flex u-break" type="text" id="artiestURL_' + i + '" placeholder="Artiestenpagina of website"><span class="js-removeArtist cell-w40 large cell-lineheigt u-pointer secondary_color-fixed"><i class="fa fa-trash-o" aria-hidden="true">R</i></span></div>').appendTo(artist);
i++;
});
$('.js-removeArtist').click(function() {
alert();
if (i > 1) {
$(this).parents('.js-artist').remove();
i--;
}
});
so if you click on the R on the newly added parts, its not working while i'm adding the same html as the one were its working
Upvotes: 0
Views: 44
Reputation: 5185
The problem is that since you are adding elements dynamically you have to bind the click event to the document since the added elements do not exist when the document is ready try:
var artist = $('#js-artist'),
i = 1;
$('#js-addArtist').click(function() {
$('<div class="js-artist u-flex-row p-top-12 u-border-top"><input class="m-left-24 small m-right-24 form-input w-100 cell-10 u-flex u-break" type="text" id="artiestNaam_' + i + '" placeholder="Artiest naam"><input class="form-input small m-right-24 w-100 cell-10 u-flex u-break" type="text" id="artiestURL_' + i + '" placeholder="Artiestenpagina of website"><span class="js-removeArtist cell-w40 large cell-lineheigt u-pointer secondary_color-fixed"><i class="fa fa-trash-o" aria-hidden="true">R</i></span></div>').appendTo(artist);
i++;
});
$(document).on('click', '.js-removeArtist', function() {
alert();
if (i > 1) {
$(this).parents('.js-artist').remove();
i--;
}
});
Here is the updated jsfiddle
https://jsfiddle.net/3kcoxsac/3/
Upvotes: 2