0

I have some div elements which I want to be able to be sorted based on their children.

I sought something that showed a certain class whilst hiding the rest, using jQuery without any plugins. I came across this Toggle multiple Div names/content by one button click which was extremely helpful in doing just that. However, I also want the sorted elements to appear in alphabetical order as well, depending on the specified class.

I attempted to use this: Jquery - sort DIV's by innerHTML of children. However, it doesn't appear to work. Any help would be immensely appreciated!

Here's what I have so far: http://jsfiddle.net/y11hr6d8/.

Here's the jQuery:

$(function() {

var $articles = $('.article');

$(".langButton").click(function() {
    var language = $(this).attr("data-language");
    $articles.hide(); // Hide them all
    $("." + language).show(); // than show the needed ones
});
});

function sortUsingNestedText(parent, childSelector, keySelector) {
    var items = parent.children(childSelector).sort(function(a, b) {
        var vA = $(keySelector, a).text();
        var vB = $(keySelector, b).text();
        return (vA < vB) ? -1 : (vA > vB) ? 1 : 0;
    });
    parent.append(items);
}

$('#sEthnicity').data("sortKey", "span.article ethnicity");
$('#sGender').data("sortKey", "span.article gender");
$('#sPet').data("sortKey", "span.article pet");
$('#sSubject').data("sortKey", "span.article subject");

$("button.langButton").click(function() {
    sortUsingNestedText($('#sortThis'), "div", $(this).data("sortKey"));
});
Community
  • 1
  • 1
Alcove
  • 39
  • 1
  • 5

2 Answers2

0

Your sortKey data values are wrong, those values are in div with classes article and ethnicity, gender, pet or subject. Also the ID used to select the buttons are wrong

$('#sblood').data("sortKey", "div.article.ethnicity");
$('#sgroup').data("sortKey", "div.article.gender");
$('#scanon').data("sortKey", "div.article.pet");
$('#sability').data("sortKey", "div.article.subject");

Demo: Fiddle

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
0
    $(function() {
        var $articles = $('.article');
        $(".langButton").click(function(){
            var language = $(this).attr("data-language");
            $articles.hide();                  // Hide them all
            $("."+ language ).show(); // than show the needed ones
        });
    });

    function sortUsingNestedText(parent, childSelector, keySelector) {
        var items = parent.children(childSelector).sort(function(a, b) {
            var vA = $(a).find("."+keySelector).text();
            var vB = $(b).find("."+keySelector).text();
            return (vA < vB) ? -1 : (vA > vB) ? 1 : 0;
        });
        parent.append(items);
    }


    $("button.langButton").click(function() {
        sortUsingNestedText($('#sortThis'), "div",  $(this).data("language"));
    });
Vishwajeet Bose
  • 430
  • 3
  • 12