MichaelHHDK
MichaelHHDK

Reputation: 21

Filtering list based on select value and css class on div

I am working on a list where I need to filter the list based on a value selected in my dropdown list. All the classes and select option values are dynamic. But always the same. Like this:

<select id="picker" onchange="changeList()">
    <option value="0">Pick a side</option>
    <option value="The-good">The good</option>
    <option value="The-bad">The bad</option>
    <option value="The-ugly">The ugly</option>
</select>

<div class="The-good">
    <span>Superman</span>
</div>

I am using jQuery to do this. So far my JS looks like this:

function changeList() {
    var selectedGroup = $("#picker").val();
    if ($("div").hasClass(selectedGroup)) {
        $("div").show();
    }
    else {
        $("div").hide();
    }
}

But that's not working. Is there a way to pick the class from the div and put it in a var and then compare the two values in my if statement?

Upvotes: 2

Views: 2037

Answers (3)

Vijay
Vijay

Reputation: 11

Try this.

function changeList() {
        $('.children').hide();
        $('.' + ($('#picker').val())).show();
    }


<select id="picker" onchange="changeList()">
    <option value="0">Pick a side</option>
    <option value="The-good">The good</option>
    <option value="The-bad">The bad</option>
    <option value="The-ugly">The ugly</option>
</select>

<div class="children The-good" style="display:none">
    <hr />
    <span>Superman</span>
</div>

<div class="children The-bad" style="display:none">
    <hr />
    <span>Badman</span>
</div>

<div class="children The-ugly" style="display:none">
    <hr />
    <span>Uglyman</span>
</div>

Upvotes: 0

Kolban
Kolban

Reputation: 15266

Following along in your original design, the following code fragment will work:

function changeList() {
    var selectedGroup = $("#picker").val();
    $("div").each(function(i, item) {
         if ($(item).hasClass(selectedGroup)) {
             $(item).show();
         } else {
             $(item).hide();
         }
    });
}

Upvotes: 0

Aditya Peshave
Aditya Peshave

Reputation: 667

If the Value is the class , then you can simply do this:

function changeList() {
                var selectedGroup = $("#picker").val();
                $('.' + selectedGroup).toggle();  
            }

Upvotes: 1

Related Questions