Carlos Serret Carlos Serret - 4 months ago 8
jQuery Question

jQuery - deleting list items

I'm trying to remove every li I click on. This is the ordered list I have:

<ol id="list">
<li id="0" class="newItems" onclick="Removeli();">G6000BJ</li>
<li id="1" class="newItems" onclick="Removeli();">G6000Bk</li>
<li id="2" class="newItems" onclick="Removeli();">G6000BN</li>
<li id="3" class="newItems" onclick="Removeli();">G6000BW</li>
<li id="4" class="newItems" onclick="Removeli();">G6000BT</li>
<li id="5" class="newItems" onclick="Removeli();">G6000BR</li>
<li id="6" class="newItems" onclick="Removeli();">G6000BE</li>
</ol>


and this the jQuery code I'm using:

function Removeli() {
$('.newItems').click(function () {
$(this).remove();
});
}


But I am not able to delete the last one when I click on it. This means that when I'm left with only one, I can't delete it. But everything else works fine.
What am I doing wrong?

Answer

You're mixing up inline JS and jQuery event binding. What's happening is that when you click on an element it calls the onclick handler, which then binds all the jQuery click handlers. The next time you click on something, it calls removbeIt() again, which binds the jQuery handlers again, and then calls the jQuery handler. But the jQuery handler doesn't get called the first time, because it hasn't been bound to the elements yet.

You shouldn't have the onclick attribute in the elements, just put the event binding in the $(document).ready() handler:

$(document).ready(function() {
    $('.newItems').click(function () {
        $(this).remove();
    });
});

Also, if you're creating the elements dynamically, you need to use event delegation instead of binding.

$(document).ready(function() {
    $("#list").on("click", ".newItems", function () {
        $(this).remove();
    });
});

See Event binding on dynamically created elements?

Comments