Rustam Rustam - 4 days ago 6
HTML Question

how to remove li element

I have folllowing funtion:

function addPhone()
{
var value= $('#Membership_c_tel').val();

$.ajax({
url: '/cabinet/membership/addPhone',
type: 'POST',
cache: false,
data: {'val':value},
beforeSend: function() {
},
success: function (r) {
var val=document.getElementById("Membership_c_tel").value;
$("#newly_create_tel").append("<li class="+val+">"+document.getElementById("Membership_c_tel").value+"<a href='#' class=''>x</a></li>");
$('#Membership_c_tel').val('');


},
error: function (e) {
console.log(e);
}
});

}


The function is responsible for adding
<li>
to
<ul id="newly_create_tel ">
when user submit data using inputbox with id=Membership_c_tel. At the same time
<a href="#">x</a>
is also added with
<li>
. The problem is i do not know how to delete specific
<li>
element when x pressed. How can i achieve to it? Help me.

$('#newly_create_tel li a').click(function(event){
event.preventDefault();

});

Answer

You need to use event delegation since it's dynamically generated and get li using parent() or closest() method.

$('#newly_create_tel').on('click', 'li a', function(event){
   event.preventDefault();
   $(this).parent().remove();
});
Comments