Nevin Thomas
Nevin Thomas

Reputation: 826

sort li elements using javascript or jquery

In my page i have the the folowing. I need to sort it out using javascript.

<li class="cat2 lang1">Hello</li>
<li class="cat2 lang1">Hello</li>
<li class="cat1 lang2">Hello</li>
<li class="cat3 lang3">Hello</li>

what i tried is:

$('#movieFeatureFilter span#selGenre .subMenus li').click(function()
{
    if(this.id != '')
    {
        $('.movie_lists ul li').hide();
        $('.movie_lists ul li.cat'+this.id).show();
    }
    else $('.movie_lists ul li').show();
});

this works perfect. but what i need to sort the list using the combination of lang and cat.

ie if i select cat1 as category and lang2 as language then it might show the third li

i think you got wht i mean. sorry for the bad explanention. help me pls

Upvotes: 0

Views: 183

Answers (2)

Arun P Johny
Arun P Johny

Reputation: 388316

var $items = $('ul li'), $cat = $('#cat'), $lang = $('#lang');
$('#cat, #lang').change(function(){
    var cat = $cat.val(), lang = $lang.val(), $filtered = $items;
    if(cat){
        $filtered = $filtered.filter('.' + cat);
    }
    if(lang){
        $filtered = $filtered.filter('.' + lang);
    }
    $items.not($filtered).hide();
    $filtered.show()
})

Demo: Fiddle

Upvotes: 2

TheVillageIdiot
TheVillageIdiot

Reputation: 40497

Seems instead of sorting you want to show/hide items based on selection of cat and lang. Following function will serve your purpose:

$("#movieFeatureFilter span#selGenre .subMenus li").click(function () {

   /*GET cat AND lang FROM DROPDOWNS*/

    var cat = $("#c").val(),
        lng = $("#l").val();

    $("#<ID OF UL> li").filter(function () {
        $this = $(this);
        if ($this.hasClass(cat)) {
            if (!$this.hasClass(lng)) {
                $this.hide();
            } else {
                $this.show();
            }
        } else {
            $this.hide();
        }
    });
});

Check in the fiddle here.

Upvotes: 0

Related Questions