Rustam
Rustam

Reputation: 273

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();

                });

Upvotes: 1

Views: 540

Answers (3)

user777
user777

Reputation: 87

inside click function write $(this).parent().remove; it worked for me

Upvotes: 1

Daimos
Daimos

Reputation: 1473

Try to create li element and assign click function right after that:

var $element = $('</li>).append($('#Membership_c_tel').val());
$element.append('<a/>', {href:'#', text:'x'});
$element.click(function(){
    // closests will be best if you plan to change your html inside li
    $(this).closests('li').remove();
    return false;
});
$element.appendTo($("#newly_create_tel"));

You have more controll and you dont use any events when you dont really need them

Upvotes: 0

Pranav C Balan
Pranav C Balan

Reputation: 115212

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();
});

Upvotes: 6

Related Questions