Rocky Rocky - 28 days ago 8
jQuery Question

How to add ul li to div on textbox change and remove ul li from div with Jquery

I have a form in which on textbox change event I need to create ul and li with textbox text and if user wants to remove the added item then user should able to remove with one confirmation.

I am able to add the ul and li with below jquery but I want to know how to remove specific (item with user wants to remove) ul and li from the div.

<div id="divDynamic"></div>

$('#txtItem').blur(function () {
var addedItems = [];
var text = $(this).val();
if ($('li:contains(' + text + ')').length === 0) {
var _tempUL = $('<ul/>').addClass('navlist');
$("#divDynamic").append(_tempUL);
var liText = $('<li/>').addClass('btn-gradient').html(text);
_tempUL.append(liText);
_tempUL.append('<li class="close"><a href="#"><img src="/Images/close.png" /></a></li>');
addedItems.push(text);
}
});


Some one please help me. Thanks in advance

Answer

You need to Replace below line

_tempUL.append('<li class="close"><a href="#"><img src="/Images/close.png" /></a></li>');

to

_tempUL.append('<li class="close"><a href="#" class="removeLi"><img src="/Images/close.png" /></a></li>');

then put this jQuery code

$(document).on( 'click', '.removeLi', function() {

    $(this).parent().prev('li.btn-gradient').remove();
    $(this).parent().remove();

});