In add new Phone number page in my website i wanna let users can have multiple phone numbers. here i have is HTML code:
<div class="d-flex align-items-center justify-content-between">
<input class="textfield" placeholder="Phone Number..." type="number" />
<button class="btn btn-primary me-1" id="addNewTelephone">
<i class="fa-regular fa-plus fs-6"></i>
</button>
</div>
<div class="d-flex align-items-center justify-content-between mt-2">
<input class="textfield" placeholder="Phone Number..." type="number" />
<button class="btn btn-danger me-1 deleteAddition">
<i class="fa-regular fa-minus fs-6"></i>
</button>
</div>
First one is the necessary number that always is visible in the page but second one is an addition number that is not exist in our page unless user click the #addNewTelephone
button.
In all addition number containers we have a button with deleteAddition
class that can remove its parent(the addition nubmer) form page but its just works when we added the addition container in out code and if user add them using #addNewTelephone
button, .deleteAddition
wont working for remove those added containers.
also here is my js(Jquery) code (#telephoneContainer is the main container for all numbers):
$('#addNewTelephone').click(function (e) {
$('#telephoneContainer').append($('<div>',{class:'d-flex align-items-center justify-content-between mt-2'}).append($('<input>', {class:"textfield", placeholder:"Phone Number...", type:"number"}),$('<button>',{class:"btn btn-danger me-1"}).append($('<i>',{class:"fa-regular fa-minus fs-6"}))),);
});
$('.deleteAddition').click(function (e) {
$(this).parent().remove();
});
I want users can add new number also can remove them using these two buttons
2
Answers
Yes delete will not work because i has appeared after all JS has been rendered so you need to do this in this way
https://stackoverflow.com/a/14879381/23284882
As elements (
.deleteAddition
) are dynamically added, you need to use event delegation.Demo: