Nevi Nevi - 2 months ago 6
jQuery Question

jQuery List Item Remove

i got this code written a few minutes ago I was wondering if why won't the item be removed.



(function($){
$('#btn1').click(function(){
var textVal = $('#input').val()
if (textVal != ""){
$('#list').append('<li class="class1" id="' + textVal + '">' + textVal + '<input type="hidden" name="Tags" value="' + textVal + '" /> <input type="button" class="remove-item" value="X"></input></li> ');
}
});
$('.remove-item').click(function (){
$('.list #' + textVal).remove()
});
})(jQuery);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="input" type="text" />
<input type="button" id="btn1" value="Add" />

<ul id="list">
</ul>




Answer

Try this code :

  var textVal;
    $('#btn1').click(function(){
    		textVal = $('#input').val()
        if (textVal != ""){
 $('#list').append('<li class="class1" id="' + textVal + '">' + textVal + '<input type="hidden" name="Tags" value="' + textVal + '" /> <input type="button" class="remove-item" id='+textVal+' value="X"></input></li> ');
          
    $('#'+ textVal +' .remove-item' ).click(function (e){
    $(e.target).parent().remove();
    });
          
        }
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="input" type="text" />
    <input type="button" id="btn1" value="Add" />

    <ul id="list">
    </ul>

Also i would suggest to use Backbone.js (Based on MVC) for such Apps

Comments