thesowismine
thesowismine

Reputation: 930

JS not working as expected when selecting options from dropdown

Goal

  1. clicking on a member of the <ul> selects/deselects it.

  2. if class=allSearch is selected any other li's that are already selected are de-selected.

  3. if allSearch is selected and then notAllSearch is selected, allSearch is deselected.

Problem

Goal 3 is not working, which doesn't make sense to me because it should be (and is) basically the same code used in Goal 2.

Here's the code:

HTML

<ul class="menu vertical" id="searchMenu">
    <li id="allSearch" class="allSearch selected">All</li>
    <li id="notAllSearch" class="notAllSearch">User</li>
    <li id="notAllSearch" class="notAllSearch">Artists</li>
    <li id="notAllSearch" class="notAllSearch">Events</li>
</ul>

JS:

$(document).ready(function() {
$('#searchMenu li').click(function () {
    if ($(this).hasClass('selected')) {
        $(this).removeClass('selected');
        }
    else if ($(this).hasClass('notAllSearch')) {
        $('#allSearch').removeClass('selected')
        $(this).addClass('selected');
    }
    else if ($(this).hasClass('allSearch')) {
        $('#notAllSearch').removeClass('selected')
        $(this).addClass('selected');
    }
    else
        $(this).addClass('selected');
});
})

Upvotes: 0

Views: 34

Answers (1)

kanudo
kanudo

Reputation: 2219

Try this : instead of ID work on CLASS for this

$(document).ready(function() {
$('#searchMenu li').click(function () {
    if ($(this).hasClass('selected')) {
        $(this).removeClass('selected');
    }
    else if ($(this).hasClass('notAllSearch')) {
        $('.allSearch').removeClass('selected')
        $(this).addClass('selected');
    }
    else if ($(this).hasClass('allSearch')) {
        $('.notAllSearch').removeClass('selected')
        $(this).addClass('selected');
        }
    else
        $(this).addClass('selected');
    });
});

Here is the pen to test

Upvotes: 1

Related Questions