jQuery issue with ul li

I am trying to convert select to ul li by using jQuery, but for some reason it won't work properly. When the Worlds button is clicked, a list will be displayed. For each time someone selects an item from the list, a green overlay will be displayed over the item (look in the picture below).

Here's the issue: When you select items multiple times, the green overlay displays on all items, as seen below. It is only supposed to display once per item clicked, just as if I were toggling it on/off.

Expected result: http://jsfiddle.net/Starx/a6NJk/2/

Actual result:
enter image description here

$("#worldBtn").on("click", function() {
   $('#displayWorlds').toggle();
});

var allOptions = $("#worlds-dropdown li");

$("ul").on("click", "li", function() {
   console.log("clicked");
   allOptions.removeClass('selected');
   $(this).addClass('selected');
   $("ul").children('#displayWorlds').html($(this).html());
   allOptions.toggle();
});

$("#worldsClose").click(function (a) {
   $('#displayWorlds').toggle();
   a.preventDefault();
});
.selected {
background-color: rgba(16, 246, 136, 0.47);
color: white;
}

li {
padding: 8px 16px;
border-radius: 6px;
line-height: 1.429;
-webkit-transition: .25s;
transition: .25s;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button id="worldBtn" type="button" class="btn btn-purple">Worlds <i class="fa fa-globe"></i></button>

<div class="bitblobs-panel bitblobs-side-panel bitblobs-worlds-panel" id="displayWorlds" style="display: none;">
<ul class="worlds-dropdown custom-scrollbar" id="worldsClose">
    <li onclick="setserver('server.localhost:551');">
        <div class="worlds-text">Option 1</div>
    </li>
    <li onclick="setserver('server.localhost:551');">
        <div class="worlds-text">Option 2</div>
    </li>

Answers 1

  • Try this jquery code to remove all selected class in all worlds-dropdown li

     $("ul").on("click", "li", function() {
    
        $(".worlds-dropdown li").each(function(){
            $(this).removeClass('selected');
        });
    
     });
    

Related Articles