Hi, i want to sort divs alphabetically both asc and desc. I am using a dropdown list created by using bootstrap:

<div class="btn-group">
    <a href="#" data-target="dropdown-menu" class="btn btn-default btn-block dropdown-toggle" data-toggle="dropdown">
    Sort By
    <span class="caret"></span>
    </a>
    <ul class="dropdown-menu" style="width: 100%;">
       <li><a href="#" class="nameAsc">Name: A to Z</a></li>
       <li><a href="#" class="nameDes">Name: Z to A</a></li>
       <li><a href="#" class="priceAsc">Price: Low to High</a></li>
       <li><a href="#" class="priceDes">Price: High to Low</a></li>
    </ul>
</div>

and my divs i want to sort are populated with data from database:

<div class="gallery_product col-lg-4 col-md-4 col-sm-4 col-xs-6 filter">
   <a href="products_details.php?pid=<?php echo $row['fld_product_id']; ?>" class="btn btn-warning btn-xs" role="button"><img src="products/<?php echo $row['fld_product_img'] ?>" class="img-responsive"></a>
   <p class="product-name"><?php echo $row['fld_product_name'] ?></p>
   <p class="product-price">RM <?php echo $row['fld_product_price'] ?></p>
</div>

Im kind of confused on how to go about it. because i want to sort the div but it needs to find the product name in <p> which is in the div. how would it find the name so it can sort?

$(".nameAsc").click(function(){
     var $name = $(".product-name");
     var $divToSort = $(".gallery_product");

     var $sort = $divToSort.sort(function(a, b){
            //what goes in here?
     });
});

Also insert the name and the price from your database in data attributes. Something like this:

<p class="product-name" data-name="<?php echo $row['fld_product_name'] ?>"><?php echo $row['fld_product_name'] ?></p>
<p class="product-price" data-price="<?php echo $row['fld_product_price'] ?>">RM <?php echo $row['fld_product_price'] ?></p>

BUT... you will need to replace the white spaces with dashes and convert to lowercase, before you insert them into your data attributes.
https://stackoverflow.com/questions/11330480/strip-php-variable-replace-white-spaces-with-dashes.

Or you could do this is also within your jquery function.
https://stackoverflow.com/questions/1983648/replace-space-with-dash-and-make-all-letters-lower-case-using-javascript

Now you can sort based on the values of the data attributes.

Here's an example for price:
https://codepen.io/glensargent/pen/zqwbqZ

For alphabetical sorting there are probably also examples to find.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.