-1

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?

2 Answers2

0

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?

Community
  • 1
  • 1
Barmar
  • 741,623
  • 53
  • 500
  • 612
-1

Pass the function to event handling

$('.newItems').click(function() {
  $(this).remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ol id="list">
  <li id="0" class="newItems">G6000BJ</li>
  <li id="1" class="newItems">G6000Bk</li>
  <li id="2" class="newItems">G6000BN</li>
  <li id="3" class="newItems">G6000BW</li>
  <li id="4" class="newItems">G6000BT</li>
  <li id="5" class="newItems">G6000BR</li>
  <li id="6" class="newItems">G6000BE</li>
</ol>
Rui Costa
  • 800
  • 4
  • 13