views:

1143

answers:

2

I have a listing of home information in the format below.

<div id="content">
    <div class="listing">
     <div class="photo"><a href="#"><img src="img.jpg" width="200"></a></div>
     <div class="info">
      <p class="address"><a href="#">321 Main St<br>Beverly Hills, CA 90210</a></p>
      <div class="attr">Price</div>
      <div class="val price">$325,000</div>
      <div class="attr">Sq. Ft.</div>
      <div class="val">2,600</div>
      <div class="attr">Built</div>
      <div class="val">1988</div>
      <div class="attr">Bedrooms</div>
      <div class="val">3</div>
      <div class="attr">Bathrooms</div>
      <div class="val">2.5</div>
     </div>
    </div>
    <div class="listing">{ANOTHER HOME LISTING...}</div>
    <div class="listing">{ANOTHER HOME LISTING...}</div>
    <div class="listing">{ANOTHER HOME LISTING...}</div>
</div>

Using JavaScript, how do I sort (on price) the listing of homes above.

To give an example, I essentially want to the do the following demo (but not use a TABLE).

http://sam-i-am.com/work/sandbox/dojo0.9/samiam/sortableList.html

+6  A: 

I am assuming you want to resort the data at the user's request after it has initially been rendered. I usually do this server-side via AJAX, i.e., do a GET request for the same dataset with different sorting. This is necessary when paging data, because after sorting the records which get displayed may be totally different than the ones previously displayed.

If you have a small dataset that is not paged and you want to sort client-side, I would render the data as a javascript array and populate your DIVs via javascript. Then, when the user wants to sort, you resort the array and call your javascript rendering function again to get your data in the newly sorted order.

RedFilter
How do I sort an array with multiple attributes? Because arrary.sort() in this case then doesn't know what to sort.
JavaScript's Array.sort() accepts a callback function which you can use to sort complex objects. See: http://www.javascriptkit.com/javatutors/arraysort.shtml
AaronSieb
See http://www.breakingpar.com/bkp/home.nsf/0/87256B280015193F87256C8D00514FA4 for an example.
RedFilter
+1  A: 

I agree with OrbMan. Store the listings in an array. You can then simply sort the array, instead of doing it all in the DOM with fancy Javascript.

On an unrelated note, do you have to use divs for everything? If you used an (un)ordered list, it would be better semantically and potentially make any Javascript you wrote easier to read and maintain. Instead of referencing a bunch of specifically-classed divs, you could reference li within a (classed) ul/ol.

Evan Meagher