Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting Elements from different DIV's

I have 3 div columns as below

<div class="col col-4 clist">
 <div data-seq="3">3</div>
 <div data-seq="5">5</div>
 <div data-seq="9">9</div>
</div>
<div class="col col-4 clist">
 <div data-seq="8">8</div>
 <div data-seq="7">7</div>
 <div data-seq="1">1</div>
</div>
<div class="col col-4 clist">
 <div data-seq="4">4</div>
 <div data-seq="2">2</div>
 <div data-seq="6">6</div>
</div>

I want to sort this inner div's in ascending order as 1 2 3 4 5 6 7 8 9. It doesn't matter if it all get sorted and displayed in a single div and/or displayed in 3 different div's. For the same purpose I am using the below written js from http://jsfiddle.net/f5mC9/

var contacts = $('div.clist'), cont = contacts.children('div');

cont.detach().sort(function(a, b) {
            var astts = $(a).data('seq');
            var bstts = $(b).data('seq')
            //return astts - bstts;
            return (astts > bstts) ? (astts > bstts) ? 1 : 0 : -1;
        });

contacts.append(cont);

I am not able to sort elements from different div's. If all the elements are in single div the code works.

Please help me out.

And heartfully thanks in advance.

like image 407
dhpratik Avatar asked May 14 '14 07:05

dhpratik


2 Answers

You need to loop over each .clist element using each() and sort the child div elements within it. Something like this:

$('div.clist').each(function () {
    var $cont = $(this).children('div').sort(function (a, b) {
        return ($(a).data('seq') > $(b).data('seq')) ? 1 : -1;
    });
    $(this).append($cont);
});

Example fiddle

like image 162
Rory McCrossan Avatar answered Nov 11 '22 09:11

Rory McCrossan


Since you're fine with the results being in a single div, simply extract all the fields into a new div first:

<div id="result">
</div>

$('div.clist').each(function() {
    $('#result').html($('#result').html() + $(this).html());
});

Then go about your business and just sort it:

var $cont = $('#result').children('div').sort(function (a, b) {
    var astts = $(a).data('seq');
    var bstts = $(b).data('seq')
    return (astts > bstts) ? 1 : -1;
});

$('#result').append($cont);

JSFiddle: http://jsfiddle.net/pSC98/1/

like image 45
peteykun Avatar answered Nov 11 '22 10:11

peteykun